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.
You should check the docs again.
forkcreates 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
forkwould fail. There wouldn’t be a stack position forpidunless the stack (including stack pointer) was duplicated.