Consider two processes, A and B, with standard input and output streams connected to each other via pipes to form a closed loop. Suppose that, as a result of an exec, the two processes are not directly aware of their relationship with each other.
If B is abruptly terminated (e.g. by sending it a SIGKILL
), how can A know that B died? Or at least, make A died too
As I understand you, the only thing you have to work with is the pipes. Nothing else that might help you carries across an exec, especially if we suppose that the program running in process A is not specifically designed for this interaction. Let us therefore consider what you can do with the pipes.
When B terminates, for whatever reason, all its open file handles are closed. That includes its handles on the pipe ends.
If A thereafter attempts to write to its own stdout
, and the read end is not open in any process,* then A will receive a SIGPIPE
, as @indianant observed. The default disposition for that signal is to terminate the process, so A will then die too unless it has changed the disposition for that signal. Whether A changes the disposition of SIGPIPE
is out of your control unless the program running in A is one you've provided.
But perhaps A will be blocked reading from its standard input when B terminates. Supposing that B was the only process holding the write end of that pipe open, A will then see EOF on its standard input. This will not automatically cause A to terminate, but it can respond appropriately to that event, which might cause it to terminate naturally. Additionally, A may first receive data written by B before its termination; if A responds by trying to write to its standard output, then the previous paragraph applies.
None of that applies, however, unless A is actually performing I/O on its standard streams. If you're looking for some kind of asynchronous notification, then you probably need to make that the responsibility of a third process. It would be easiest for that purpose to give A and B a common parent process, possibly one dedicated to the purpose. The parent will be notified via a SIGCHLD
or by returning from a wait()
or waitpid()
when one of its children dies; it could then take appropriate action such as killing the other child. Note that this does not work for A being the parent of B, or vise versa
, because signal handlers are not carried over an exec, except possibly SIG_IGN
for SIGCHLD
.
*In particular, make sure the read end is not open in A by closing it before the exec.