summaryrefslogtreecommitdiff
path: root/src/signals.cc
blob: 9f8bff77a62556b0b5f3283ca361aafbe6735393 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include "signals.hh"

#include "looper.hh"
#include "unique_pipe.hh"

#include <cerrno>
#include <csignal>
#include <cstdint>
#include <functional>
#include <memory>
#include <unistd.h>
#include <unordered_map>
#include <utility>

namespace signals {

namespace {

std::unordered_map<int, int> g_fds;

int signum(Signal signal) {
  switch (signal) {
    case Signal::INT:
      return SIGINT;
    case Signal::TERM:
      return SIGTERM;
  }
  std::unreachable();
}

void signal_handler(int signum) {
  auto it = g_fds.find(signum);
  if (it != g_fds.end()) {
    char c = 1;
    while (true) {
      auto ret = write(it->second, &c, 1);
      if (ret < 0 && errno == EINTR)
        continue;
      break;
    }
  }
}

class HandlerImpl : public Handler {
 public:
  HandlerImpl(looper::Looper& looper, Signal signal,
              std::function<void()> callback)
      : looper_(looper),
        signal_(signum(signal)),
        callback_(std::move(callback)) {
    looper_.add(pipe_.reader(), looper::EVENT_READ,
                [this](auto event) { call(event); });
    g_fds[signal_] = pipe_.writer();

    ::signal(signal_, signal_handler);
  }

  ~HandlerImpl() override {
    ::signal(signal_, SIG_DFL);
    looper_.remove(pipe_.reader());
    g_fds.erase(signal_);
  }

 private:
  void call(uint8_t /* event */) {
    char buf[10];
    while (true) {
      auto ret = read(pipe_.reader(), buf, 10);
      if (ret < 0 && errno == EINTR)
        continue;
      break;
    }
    callback_();
  }

  unique_pipe pipe_;
  looper::Looper& looper_;
  int signal_;
  std::function<void()> callback_;
};

}  // namespace

std::unique_ptr<Handler> Handler::create(looper::Looper& looper, Signal signal,
                                         std::function<void()> callback) {
  return std::make_unique<HandlerImpl>(looper, signal, std::move(callback));
}

}  // namespace signals