blob: 1679b46da9b712a3aea3c29e6500c39920c09470 [file] [log] [blame]
Austin Schuh6c590f82019-09-11 19:23:12 -07001#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
8#include "aos/logging/logging.h"
9
10namespace aos {
11namespace ipc_lib {
12
13SignalFd::SignalFd(::std::initializer_list<int> signals) {
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.
21 PCHECK(fd_ = signalfd(-1, &mask_, SFD_NONBLOCK | SFD_CLOEXEC));
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
27SignalFd::~SignalFd() {
28 // Unwind the constructor. Unblock the signals and close the fd.
29 pthread_sigmask(SIG_UNBLOCK, &mask_, nullptr);
30 PCHECK(close(fd_));
31}
32
33signalfd_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