Search code examples
linuxsignalssystem-callsepoll

Wait for file input or a signal in Linux


I can wait for one of several network connections using select or epoll. I can wait for a signal using sigwaitinfo, or add a handler to run on receipt of the signal.

How do I wait for either a network socket to have incoming traffic, or for a specific signal (SIGWINCH, in my case)?

One idea that occurs to me is to have the signal handler send "loopback" traffic to some open file descriptor, so epoll can await it. But I'd rather not actually make any file. Maybe there's a way to create two new file descriptors which are directly connected to one another?


Solution

  • On Linux, I'd do this with signalfd(2), which creates a file descriptor that polls as readable when given signals are delivered (and can be read from to find out information about the signal). That descriptor can be added to the ones monitored by epoll, along with the sockets.

    You should block SIGWINCH first with sigprocmask(2) so it doesn't get handled by normal signal handlers.


    One idea that occurs to me is to have the signal handler send "loopback" traffic to some open file descriptor, so epoll can await it. But I'd rather not actually make any file. Maybe there's a way to create two new file descriptors which are directly connected to one another?

    You can use pipe(2) to create a pair of connected descriptors for that style; it's a common technique for this sort of scenario in older and/or portable code bases. With Linux I generally prefer the lighter weight eventfd(2) for asynchronous notifications, though.