Austin Schuh | 6c590f8 | 2019-09-11 19:23:12 -0700 | [diff] [blame] | 1 | #include "aos/ipc_lib/signalfd.h" |
| 2 | |
| 3 | #include <signal.h> |
| 4 | #include <sys/types.h> |
| 5 | #include <unistd.h> |
| 6 | #include <initializer_list> |
| 7 | |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame^] | 8 | #include "glog/logging.h" |
Austin Schuh | 6c590f8 | 2019-09-11 19:23:12 -0700 | [diff] [blame] | 9 | |
| 10 | namespace aos { |
| 11 | namespace ipc_lib { |
| 12 | |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame^] | 13 | SignalFd::SignalFd(::std::initializer_list<unsigned int> signals) { |
Austin Schuh | 6c590f8 | 2019-09-11 19:23:12 -0700 | [diff] [blame] | 14 | // Build up the mask with the provided signals. |
| 15 | sigemptyset(&mask_); |
| 16 | for (int signal : signals) { |
| 17 | sigaddset(&mask_, signal); |
| 18 | } |
| 19 | // Then build a signalfd. Make it nonblocking so it works well with an epoll |
| 20 | // loop, and have it close on exec. |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame^] | 21 | PCHECK((fd_ = signalfd(-1, &mask_, SFD_NONBLOCK | SFD_CLOEXEC)) != 0); |
Austin Schuh | 6c590f8 | 2019-09-11 19:23:12 -0700 | [diff] [blame] | 22 | // Now that we have a consumer of the signal, block the signals so the |
| 23 | // signalfd gets them. |
| 24 | pthread_sigmask(SIG_BLOCK, &mask_, nullptr); |
| 25 | } |
| 26 | |
| 27 | SignalFd::~SignalFd() { |
| 28 | // Unwind the constructor. Unblock the signals and close the fd. |
| 29 | pthread_sigmask(SIG_UNBLOCK, &mask_, nullptr); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame^] | 30 | PCHECK(close(fd_) == 0); |
Austin Schuh | 6c590f8 | 2019-09-11 19:23:12 -0700 | [diff] [blame] | 31 | } |
| 32 | |
| 33 | signalfd_siginfo SignalFd::Read() { |
| 34 | signalfd_siginfo result; |
| 35 | |
| 36 | const int ret = |
| 37 | read(fd_, static_cast<void *>(&result), sizeof(signalfd_siginfo)); |
| 38 | // If we didn't get the right amount of data, signal that there was a problem |
| 39 | // by setting the signal number to 0. |
| 40 | if (ret != static_cast<int>(sizeof(signalfd_siginfo))) { |
| 41 | result.ssi_signo = 0; |
| 42 | } |
| 43 | return result; |
| 44 | } |
| 45 | |
| 46 | } // namespace ipc_lib |
| 47 | } // namespace aos |