fork() within a fork()

Posted by codingfreak on Stack Overflow See other posts from Stack Overflow or by codingfreak
Published on 2010-03-08T13:18:57Z Indexed on 2010/03/08 13:21 UTC
Read the original article Hit count: 471

Filed under:
|
|
|

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 fpid>0 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 ??

© Stack Overflow or respective owner

Related posts about c

    Related posts about fork