Aktualizr
C++ SOTA Client
All Classes Namespaces Files Functions Variables Enumerations Enumerator Pages
sighandler_test.cc
1 #include <gtest/gtest.h>
2 
3 #include <atomic>
4 
5 #include <sys/time.h>
6 #include <sys/wait.h>
7 #include <unistd.h>
8 
9 #include "sig_handler.h"
10 
11 TEST(SigHandler, Catch) {
12  pid_t child_pid;
13  int pipefd[2];
14 
15  ASSERT_EQ(pipe(pipefd), 0);
16  if ((child_pid = fork()) == 0) {
17  // child
18  std::atomic<bool> do_exit{false};
19 
20  close(pipefd[0]);
21 
22  SigHandler::get().start([&do_exit, pipefd]() {
23  // child exited here
24  close(pipefd[1]);
25  do_exit.store(true);
26  });
27  SigHandler::signal(SIGINT);
28 
29  // signal that we're ready to be killed
30  if (write(pipefd[1], "r", 1) != 1) {
31  exit(1);
32  }
33 
34  while (true) {
35  boost::this_thread::sleep_for(boost::chrono::milliseconds(20));
36  if (do_exit.load()) {
37  break;
38  }
39  }
40  exit(0);
41  } else {
42  // parent
43  close(pipefd[1]);
44 
45  // wait for the child to be ready
46  char b = 0;
47  EXPECT_EQ(read(pipefd[0], &b, 1), 1);
48  EXPECT_EQ(b, 'r');
49 
50  // kill the child
51  kill(child_pid, SIGINT);
52 
53  // wait for child to exit
54  int status;
55  waitpid(child_pid, &status, 0);
56  EXPECT_TRUE(WIFEXITED(status));
57  }
58 }
59 
60 #ifndef __NO_MAIN__
61 int main(int argc, char **argv) {
62  ::testing::InitGoogleTest(&argc, argv);
63  return RUN_ALL_TESTS();
64 }
65 #endif
SigHandler
Definition: sig_handler.h:13