blob: af955983596de24073b738cf0827a5a2fc1bb1d7 [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
Alex Perrycb7da4b2019-08-28 19:35:56 -07008#include "glog/logging.h"
Austin Schuh6c590f82019-09-11 19:23:12 -07009
10namespace aos {
11namespace ipc_lib {
12
Alex Perrycb7da4b2019-08-28 19:35:56 -070013SignalFd::SignalFd(::std::initializer_list<unsigned int> signals) {
Austin Schuh6c590f82019-09-11 19:23:12 -070014 // 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 Perrycb7da4b2019-08-28 19:35:56 -070021 PCHECK((fd_ = signalfd(-1, &mask_, SFD_NONBLOCK | SFD_CLOEXEC)) != 0);
Austin Schuh6c590f82019-09-11 19:23:12 -070022 // 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);
Alex Perrycb7da4b2019-08-28 19:35:56 -070030 PCHECK(close(fd_) == 0);
Austin Schuh6c590f82019-09-11 19:23:12 -070031}
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