Can a parent process determine its child's status ?

Leslie Mikesell les at chinet.chi.il.us
Thu Feb 22 16:36:33 AEST 1990


In article <5090.25e135aa at mva.cs.liv.ac.uk> adh at mva.cs.liv.ac.uk writes:

>Does anyone know how a parent process can determine the status of one
>of its children if it *hasn't* executed a wait ? It could arrange to 
>catch a SIGCLD signal, but if the parent had several children it
>wouldn't know which one had sent it the SIGCLD ... would it ?

Just do a wait() inside the SIGCLD handler to pick up the PID of
the exiting child.  I think getting this right is unix-version specific.
SysV pretends to queue the SIGCLD's but in fact only delivers pending
SIGCLD's (after the first) in response to signal() being called to
re-enable SIGCLD.  Thus you must wait(), then signal(SIGCLD,handler)
inside the handler.

>My reason for asking is as follows: I need to write a program which
>starts several children and reads from their respective stdout's via
>pipes. The children are executing simultaneously, so the parent uses
>non-blocking reads, polling each pipe to see if anything has arrived.
>Unfortunately, a call to 'read' returns zero if the child hasn't
>sent any new data *OR* if the child has terminated so the parent cannot
>distinguish between EOF on a pipe and a pipe that temporarily has no
>data in it.

If the children are your own programs or you can stick another process
in the middle, you could "packetize" the data to indicate the source
and write it to a single pipe, allowing the reader to block instead
of polling.  Using a fixed-length header consisting of <pid><length>
followed by a variable amount of data should work for most purposes.
The header and following data must be written in a single write() and
must be less than PIPE_MAX in length (generally 5 or 10K) to insure
that the various writers keep their packet boundaries intact.  A <length>
field of 0 could indicate that the process is finished (i.e. EOF on its
stream).  The reader can either read the headers followed by a read()
of the appropriate length for the data (which has to already be in the
pipe since it was written in the same write() as the header), or
more efficiently, attempt to read() in large chunks and parse out the
results from the buffer.
If you have FIFO's (named pipes) this arrangement can be set up without
having a common parent.
 
Les Mikesell
 les at chinet.chi.il.us



More information about the Comp.unix.questions mailing list