Belle II Software development
Fork.h
1/**************************************************************************
2 * basf2 (Belle II Analysis Software Framework) *
3 * Author: The Belle II Collaboration *
4 * *
5 * See git log for contributors and copyright holders. *
6 * This file is licensed under LGPL-3.0, see LICENSE.md. *
7 **************************************************************************/
8#ifndef _Belle2_Fork_hh
9#define _Belle2_Fork_hh
10
11#include <unistd.h>
12#include <signal.h>
13#include <sys/wait.h>
14#include <stdlib.h>
15
16namespace Belle2 {
22 class Fork {
23
24 public:
25 template <class WORKER>
26 static void g_handler_exit(int, void* worker)
27 {
28 delete(WORKER*)worker;
29 exit(0);
30 }
31 static void g_handler_int(int) { exit(0); }
32
33 public:
34 Fork() : m_pid(-1) {}
35
36 template<class WORKER>
37 Fork(WORKER* worker, bool detached = true)
38 {
39 m_pid = fork();
40 if (m_pid == 0) {
41 signal(SIGINT, g_handler_int);
42 if (detached) {
43 on_exit(g_handler_exit<WORKER>, (void*)worker);
44 }
45 worker->run();
46 exit(0);
47 } else if (detached) {
48 delete worker;
49 }
50 }
51 ~Fork() {}
52
53 public:
54 pid_t get_id() const { return m_pid; }
55 void set_id(pid_t id) { m_pid = id; }
56 bool isAlive() const { return kill(0); }
57 bool kill(int signo) const
58 {
59 if (m_pid < 0) return false;
60 return ::kill(m_pid, signo) == 0;
61 }
62 bool wait(int opt = 0)
63 {
64 if (m_pid < 0) return false;
65 if (::waitpid(m_pid, NULL, opt)) {
66 m_pid = -1;
67 }
68 return true;
69 }
70 bool cancel() { return kill(SIGINT); }
71
72 private:
73 pid_t m_pid;
74
75 };
76
78}
79
80#endif
Abstract base class for different kinds of events.