fork() within a fork()
- by codingfreak
Hi
Is there any way to differentiate the child processes created by different fork() functions within a program.
global variable i;
SIGCHLD handler function()
{
i--;
}
handle()
{
fork() --> FORK2
}
main()
{
while(1)
{
if(i<5)
{
i++;
if( (fpid=fork())==0) --> FORK1
handle()
else (fpid>0)
.....
}
}
}
Is there any way I can differentiate between child processes created by FORK1 and FORK2 ?? because I am trying to decrement the value of global variable 'i' in SIGCHLD handler function and it should be decremented only for the processes created by FORK1 ..
I tried to use an array and save the process id [this code is placed in fpid0 part] of the child processes created by FORK1 and then decrement the value of 'i' only if the process id of dead child is within the array ... But this didn't work out as sometimes child processes dead so fastly that updating the array is not done perfectly and everything messed up.
So is there any better solution for this problem ??