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 of the child processes created by FORK1 and this is done by the parent process. I will decrement the value of ‘i’ only if the process id of dead child is within the array …
But I faced a problem with the following scenario
child1, parent1, child1 killed, child2, child2 killed, parent2
Incase of child1 since it is killed after parent1 the array is updated properly.
But what in the case of child2 which gets killed before its pid value get updated by parent2 in the array? Inside SIGCHLD signal handler function since child2 PID value is not in the array the ‘i’ value is not getting decremented accordingly ..
So is there any better solution for this problem ??
Since you’re already saving a list of PIDs for which you want to decrement the value of
iin theSIGCHLDhandler, the part that may be tripping you up is receiving an additionalSIGCHLDwhile updating the list.You can mask/block additional
SIGCHLDsignals during execution of the signal handler usingsigprocmask(). This should provide you sufficient time to update your array/list of process IDs without worrying about receiving anotherSIGCHLD. The blocked mask must be returned to its original value when the signal handling routine has finished.Try adding something similar to the following to your
SIGCHLDhandler:Update
After re-examining your question, I see that you have a race conditon in which a child process terminates before the parent process can add its PID to the list.
One possible solution is still to use
sigprocmask()to block theSIGCHLDsignal during the critical section. In this case, you will need to block theSIGCHLDsignal before your call tofork()and unblock it in the parent code after the PID has been added to the list. If the child dies, the signal handler will be called after you unblock the signal and this should guarantee that the PID is in the list.