clinuxpipewaitpid

Select, pipe and waitpid - how to wait for specific child?


He is the deal: I have n fork, in fork I have exec, everything is connect with pipe.
My question:
If some child do exit() I want to close his pipe to be able to read. - how to do this? Waitpid most likely...

Now I wait for all child like that:

for(i = 0; i< val; i++)
        {
                wait(&status);
                close(fd[i][1]);
        }

val - numbers of child.


Solution

  • When you fork, the parent receives the pid of the child. You need to keep these pids in some data structure (a hash table or a linked list, perhaps). You should also keep the pipe-fd associated with that pid. So perhaps a datastructure like:

    typedef struct pidsnpipes pidsnpipes;
    struct pidsnpipes {
        pidsnpipes * next;       /* for linked list */
        pid_t        childpid;
        int          pipefd;     /* parents end of this pipe */
        int          status;     /* if you want to remember the child's exit status */
    };
    
    pidsnpipes * childprocs = NULL;
    

    When wait() returns you get the pid of the child which exited (and optionally, its exit status). Use that to lookup which pipe went with that process so you close the right pipe.