This is a homework question. I have to write a program forking itself 20 times. Each new process is adding +1 to a variable (integer) which is shared between all of them. The thing is, I have to use semaphores (IPC). This piece of code is ‘working’ – giving the value of 20 in the end.
*buf = 0;
for(i=1; i<=20; ++i)
{
if(fork()!=0)
{
*buf += 1;
exit(0);
}
}
EDIT:
Based on this code I am trying to get output like :
I am child 1…
I am child 2…
.
.
.
I am child 20…
It worked once (first time), and then the order became random. But I did not change any code. What am I doing wrong?
Well your major problem is this:
fork()will return -1 on error, the parent pid, OR ZERO for the child. So you are actually doing everything in the parent. Change to (fork() ==0) and it does what you want.Also you should wait on your children and detach shared memory. (I added some output of the process ids to make it a little clearer.)