Search code examples
cforkwaitmkfifo

Multiple forks, wait for the first to finish


I'm kind of new to all the fork, exec and wait functions. I have an assignment, which requires I fork my main process i times and then use all the children to write on to different fifos for each process. For example, if I have 3 children, I'll have to write to 3 different fifos. Then, my parent process has to wait for the first one to finish writing on any fifo, and read the data from that specific fifo. What baffled me is that my parent process has to wait for the first to finish and not for all the processes to finish. If I had to wait for all, I would use while(wait(NULL)>0). However what do you do in this case? I've written a sample code below:

pid_t *pid;
int    i;

pid = malloc(sizeof(pid_t)*children);
for(i=0;i<children;i++)
{
     if((pid[i]=fork())<0)
     { /* error */ }

     if(pid[i]==0)
     {
          //WriteOnFifos
          return 0;
     }
     else
     {
           //wait for the first process to finish
     }
 }

Thanks in advance. Any help would be appreciated.


Solution

  • Just use wait(NULL). As the documentation says, it will wait until one of its children terminate. So it will do what you want, i.e.: wait for the first child to finish.