11 ms·
> What if you don't have an event loop though? You can use my second-favorite technique: dedicate a thread to signals. Block the signals of interest, keeping t
by scottlamb 5y ago
> What if you don't have an event loop though?
You can use my second-favorite technique: dedicate a thread to signals. Block the signals of interest, keeping them queued rather than running signal handlers. Do this early in main(), before spawning any threads, so that they'll inherit the block. Spawn a thread which dequeues in a loop via sigwaitinfo or sigtimedwait. Signal handling without a signal handler!
> Roughly? What are the differences [between the self-pipe trick and signalfd]? The most obvious to me is the fact I can read siginfo structures from the file descriptor.
That's the difference I mean. If you want to get those from the self-pipe trick, you need to do it yourself, dealing with the platform difference crap this article describes. Additionally, if you write more than one byte per signal, you'll have to be careful of half-written messages, since your signal handler can't block for capacity. (Why? It may be blocking the thread that does the reading, so it'd deadlock.) Maybe you'd have a separate buffer for the leftover part that doesn't quite fit, or ensure your your message size divides evenly into the pipe buffer capacity (see F_GETPIPE_SZ), or drop messages if there's insufficient capacity (use FIONREAD; the capacity shouldn't go down unless you're using the same pipe for multiple signals and don't have them masking each other out). Stuff like this can get complex but the basic technique of just ensuring ctrl-C reaches your event loop isn't that bad. You have to be very careful in the signal handler, but it's like five lines long, so life goes on.
Another difference is that installing a self-pipe handler lets you see the previous handler (if any). I've heard of chaining handlers to address complaints like kstenerud's about libraries. I've never actually wanted to share signals like that, but it's something one could try. Caveat: if you also want to uninstall signals, doing that out of order wouldn't go well.