IMPLEMENTATION NOTES
The pselect() function is implemented in the C library as a wrapper
around select().
That means it's not actually compliant. pselect needs to _atomically_ unblock signals so that if any signal handlers are invoked pselect returns EINTR error. User code can't emulate the correct semantics because there's a race between unblocking (i.e. changing the signal mask), checking for signal arrival, and calling select. It's _impossible_ to fix this race without resort to pselect, or by use of system extensions like kqueue on BSD/macOS[1] or signalfd on Linux, which can be tricky. On Solaris you just have to use pselect, or resort to the so-called "pipe trick".
So the fact that pselect is a wrapper around select admits that it's not conformant. It's basically useless; worse, it's dangerous because application code calling pselect expecting there won't be a race.
You can see the race with this code, which on 10.10.5 still fails. What should happen is that it exits immediately with OK. What actually happens on macOS is that its pselect wrapper unblocks the signal, which is immediately delivered. But by then we've already checked that interrupted was still 0. It then calls select, which will timeout because it won't be interrupted--the signal was already delivered. On every other platform implementing pselect (which all do it correctly), pselect will always return EINTR because the signal unmasking and delivery happens in the kernel _after_ entering select.
#include
#include
#include
#include
#include
#include
static int interrupted;
static void
interrupt(int signo)
{
interrupted = signo;
}
int
main(void)
{
struct timespec timeout = { 3, 0 };
sigset_t empty, block;
int n;
sigemptyset(&empty);
sigemptyset(&block);
sigaddset(&block, SIGHUP);
sigprocmask(SIG_BLOCK, &block, NULL);
signal(SIGHUP, &interrupt);
raise(SIGHUP);
while (!interrupted) {
/*
* If pselect does not atomically unblock signals, pselect
* will never be interrupted and we'll lose the signal until
* something else wakes us up AND we remember to check even
* though we never saw EINTR.
*/
n = pselect(0, NULL, NULL, NULL, &timeout, &empty);
if (n == -1 && errno != EINTR) {
err(1, "pselect");
} else if (n == 0) {
errx(1, "timed out");
}
}
if (interrupted != SIGHUP)
errx(1, "wrong signal (got %d, expected %d)",
interrupted, SIGHUP);
puts("OK");
return 0;
}
[1] FWIW, here's a correct implementation of pselect for macOS using kqueue. (
https://github.com/wahern/cqueues/blob/snap-20160812/src/cqu...) The only caveat is that creating a kqueue descriptor might fail, and you don't normally expect pselect to fail with EMFILE or ENFILE; it might even make it non-compliant. Except for that caveat, it's a compliant implementation of pselect AFAICT.