Segments duplicated during fork()?

2019-06-08 05:37发布

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.

2条回答
在下西门庆
2楼-- · 2019-06-08 06:17

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
查看更多
Anthone
3楼-- · 2019-06-08 06:24

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.

查看更多
登录 后发表回答