The self-pipe trick

Richard Stevens's 1992 book
``Advanced programming in the UNIX environment''
says that you can't safely
mix select() or poll() with SIGCHLD (or other signals).
The SIGCHLD might go off while select() is starting,
too early to interrupt it, too late to change its timeout.

Solution: the self-pipe trick.
Maintain a pipe and select for readability on the pipe input.
Inside the SIGCHLD handler, write a byte (non-blocking, just in case)
to the pipe output.
Done.

Of course, the Right Thing would be to have fork() return
a file descriptor, not a process ID.

History

I recall coming up with the self-pipe trick around 1990;
I see it in some code I published back then.
I described the self-pipe trick
on 1991.06.16 in comp.unix.questions
and on 1991.08.25 in comp.unix.internals.
I didn't introduce the name ``self-pipe trick'' until several years later.

You'd think that the self-pipe trick would be well known by now (2003.06).
But the Linux SELECT_TUT documentation continues to claim that pselect(),
which isn't supported by most UNIX kernels,
is ``essential'' for programs that mix signals with select().