Reputation: 173
So I am trying to understand the forking process and in the following program. I have a global integer that gets manipulated by both the parent and the child processes.
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <cstdlib>
using namespace std;
int global = 0;
int main()
{
int fork_return;
fork_return = fork();
if(fork_return == 0)
{
global++;
printf("Global value in child is: %d \n", global);
}
else
{
global--;
printf("Global value in parent is: %d \n", global);
}
return 0;
}
Inside the child process, global is 1
Inside the parent process, global is -1
My question is: How come we have a global variable and what happens to the child is basically hidden from the parent and vice versa?
My understanding is: What happens in the child is hidden from the parent and vice versa.
Why this behavior ?
Upvotes: 0
Views: 92
Reputation: 182761
The parent and child have an identical view of memory and file descriptors at the time fork
is called. After that, they are each free to go their own separate ways. The fork
operation would be unusable otherwise as any change in one process would corrupt what the other one was doing.
Upvotes: 2