开发者

Segments duplicated during fork()?

开发者 https://www.devze.com 2023-01-27 17:41 出处:网络
I have studied that during a fork, the data and code segment of the parent process gets duplicated into the child process.

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 proces开发者_如何学JAVAs 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.


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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消