After forking, are global variables shared?

前端 未结 4 572
既然无缘
既然无缘 2020-11-29 00:50

Consider this simple code:

 int myvar = 0;
 int main() {
     if (fork()>0) {
       myvar++;
     } else {
       // father do nothing
     }
 }
<         


        
4条回答
  •  既然无缘
    2020-11-29 01:21

    After fork(), the entire process, including all global variables, is duplicated. The child is an exact replica of the parent, except that it has a different PID(Process Id), a different parent, and fork() returned 0. Global variables are still global within its own process. So the answer is no, global variables are not shared between processes after a call to fork().

提交回复
热议问题