In: Computer Science
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
int global;
int main()
{
int local;
pid_t id1 = fork();
if (id1==0)
{
wait(NULL);
global=100;
local=200;
printf("Global:%d\tLocal:%d\n",global,local);
}
else
{
global=10;
local=20;
printf("Global:%d\tLocal:%d\n",global,local);
wait(NULL);
}
return 0;
}
Explanation:
if (id1==0) // if id1==0 then it is child process,
so we make it wait until parent is executed
{
wait(NULL);
global=100;
local=200;
printf("Global:%d\tLocal:%d\n",global,local);
}
// id pid>0 then it is parent process, so we
modify the variables, print them and then make the parent wait
until child also modifies variables and print
them
else
{
global=10;
local=20;
printf("Global:%d\tLocal:%d\n",global,local);
wait(NULL);
}