Segments duplicated during fork()?

Deadly 提交于 2019-12-08 06:44:56

问题


I have studied that during a fork, the data and code segment of the parent process gets duplicated into the child process.

Kindly see the program below.

int main()
{
   int a = 5;
   pid_t pid;

   pid = fork();

   if(pid == 0)
   {
      printf("In child a = %d",a);
   }

   else
   {
     printf("In parent a = %d",a);
   }

   return 0;
}

Here a is in the stack segment of parent process as it is declared inside the function, main(). The child process should only get copy of the code and data segment of the parent process and not the stack during fork(). But when I run the program, I can see that the child process is able to access the variable 'a' also. Thats means somehow the stack of parent process is also copied into the child process.

Kindly tell me the reason for this and correct me if my understanding is wrong.


回答1:


You should check the docs again. fork creates an "exact copy of the calling process". Admittedly, there are a lot of exceptions, but the stack is not one of them.

Also, if the stack wasn't duplicated, the very common idiom (also used in your code) of checking the return value (almost always a stack variable) from fork would fail. There wouldn't be a stack position for pid unless the stack (including stack pointer) was duplicated.




回答2:


That isn't a good test - as Matthew has pointed out, fork() gives you an exact copy of the parent process, including the stack (else the child would be unable to return from this function).

A better test is to modify 'a' in the parent and observe it in the child, like this:

#include <stdio.h>
#include <unistd.h>
int main()
{
    int a = 5;
    pid_t pid;

    pid = fork();

    if (pid == 0)
    {
        sleep(5);
        printf("In child a = %d\n",a);
    }
    else
    {
        a++;
        printf("In parent a = %d\n",a);
    }

    return 0;
}

and the result is correct:

pandora:~/tmp$ cc -o x x.c
pandora:~/tmp$ ./x
In parent a = 6
pandora:~/tmp$ In child a = 5


来源:https://stackoverflow.com/questions/4290559/segments-duplicated-during-fork

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!