crazy4s
asked on
does fork() process share global variables
Hi all,
As what i know when you fork() a process, parent process and child process will be able to access the same global variables.
But i'm having the issue that when i changes some values in the child process, parent process isn't taking the changed values instead it still getting the same value as i initialized at first?
Can anyone explain to me why is this happening, or do i mistaken anything?
Thanks in advance.
this code contains race condition.
output:
child: x = 0 y = 1
parent: x = 1 y = 0 <--if child runs first, shouldn't the parent x = 5 y = 1???
As what i know when you fork() a process, parent process and child process will be able to access the same global variables.
But i'm having the issue that when i changes some values in the child process, parent process isn't taking the changed values instead it still getting the same value as i initialized at first?
Can anyone explain to me why is this happening, or do i mistaken anything?
Thanks in advance.
this code contains race condition.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int x;
int y;
int main(void)
{
pid_t pid;
if( (pid = fork()) < 0)
{
perror("Fork error");
exit(1);
}
else if( pid == 0)
{
if (x == 0)
{
y = x + 1;
}
else
{
y = 5;
}
printf("child: x = %d y = %d\n", x, y);
}
else
{
if (y == 0)
{
x = y + 1;
}
else
{
x = 5;
}
printf("parent: x = %d y = %d\n", x, y);
}
exit(0);
}
output:
child: x = 0 y = 1
parent: x = 1 y = 0 <--if child runs first, shouldn't the parent x = 5 y = 1???
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
hmmm okay i'm actually doing on the race condition problem and bump into this fork problem.
oh well but did learned something new!
thank you.
oh well but did learned something new!
thank you.
ASKER
hmmm so is there any possible way that child and parent process to access the same variable? or is impossible?