After forking, are global variables shared?

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

Consider this simple code:

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


        
4条回答
  •  Happy的楠姐
    2020-11-29 01:25

    No, since global variables are not shared between processes unless some IPC mechanism is implemented. The memory space will be copied. As a consequence, the global variable in both processes will have the same value inmediately after fork, but if one changes it, the other wont see it changed.

    Threads on the other hand do share global variables.

提交回复
热议问题