[TUHS] fork

Dan Cross via TUHS tuhs at tuhs.org
Wed May 13 21:29:15 AEST 2026


On Wed, May 13, 2026 at 1:04 AM Lars Brinkhoff via TUHS <tuhs at tuhs.org> wrote:
> Folkert van Heusden wrote:
> > After a waitpid() in the signal handler, all is good.
> > Never realised that you could do that in a signal handler!
>
> Maybe you "can't".  That is, if you strictly follow the C standard.
> There are very few things you are allowed to do inside a signal handler.

In ISO C, you can't.

The rules are a bit different if you the signal handler is invoked
synchronously, but if it's not, the things the program can do that do
not result in the dreaded, "undefined behavior" are very limited.  It
can manipulate stack locals are, use values of integer type `volatile
sig_atomic_t`, use lock-free atomics, and call a handful of functions
to halt the program.

But ISO C doesn't know anything about processes, fork, SIGCHLD, or waitpid.  :-D

> POSIX relaxes the constraints considerably, and it seems waitpid is
> indeed allowed.

Yes.  Each edition of POSIX includes a defined version of ISO C as a
normative reference; for POSIX.1-2024 (properly, "The Open Group Base
Specifications Issue 8, IEEE Std 1003.1 - 2024 Edition"), that version
is C17 (aka, "ISO/IEC 9899:2018, Programming Languages - C").

The rules from ISO C still about, but functions that are what POSIX
calls, "async-signal-safe" are allowable in signal signal handlers.
`waitpid` is one of those.  There are something like 200 of them:
https://pubs.opengroup.org/onlinepubs/9799919799/functions/V2_chap02.html#tag_16_04

Btw, a fun trick to turn a signal into a synchronous event, is what is
sometimes called the, "self-pipe" trick. Here, you create a pipe, set
the write-end of it to be non-blocking, and in your signal handler,
write a byte into the pipe (you make it non-blocking so that you never
block in the signal handler, should the pipe fill up).  Then, you can
run `select` (or `poll` or whatever) in your "main loop" and add the
read-end of the pipe to the read-set you're selecting on; when you
receive a signal, that pipe will become readable, you read a byte out
of it, and you can do whatever you would have needed to do to handle
the signal in a normal context. I think Dan Bernstein was the first
person to document the idea.

        - Dan C.


More information about the TUHS mailing list