This is my program:
int a;
int main(void)
{
a=10;
//declare and create 2 pipes
int p1[2], p2[2];
pipe(p1);
pipe(p2);
int ra;
for(int i=0;i<3;i++)
{
pid=fork();
if(pid==0)
{
close(p1[1]);
close(p2[0]);
read(p1[0],&ra,3);
while(ra>0)
{
ra-=1;
printf("%i a are available, reported by process %i\n",ra,getpid());
close(p1[0]);
write(p2[1],&ra,3);
close(p2[1]);
}
break;
}
else
if(pid>0)
{
}else
{
wait(NULL);
}
}
}
if(pid>0) //parent process outside for loop
{
close(p1[0]);
close(p2[1]);
if(a>0)
{
write(p1[1],&a,3);
close(p1[1]);
}
else
exit(0);
read(p2[0],&ra,3);
a=ra;
close(p2[0]);
}
What it does is creating 6 child processes from parent process, then assigning them to access the global variable a
and decreasing it 1. These processes communicate with their parent process via two pipes. Parent process will write the value to the pipe 1. Child processes will read it from pipe 1, print it out and write it back to the pipe 2 after decreasing it 1. Finally, parent process will read the value from pipe 2 and check if the value > 0 to decide to stop the program or not.
I expect the following result:
35 seats are available, reported by process 1
34 seats are available, reported by process 2
33 seats are available, reported by process 5
32 seats are available, reported by process 0
31 seats are available, reported by process 2
....
1 seats are available, reported by process 3
0 seats are available, reported by process 1
but the actual output is:
35 seats are available, reported by process 2
34 seats are available, reported by process 2
33 seats are available, reported by process 2
32 seats are available, reported by process 2
31 seats are available, reported by process 2
....
1 seats are available, reported by process 2
0 seats are available, reported by process 2
Question: I dont know how to force other child processes running alternatively (or randomly) so the result would be like the first one above. Please help me.