Belle II Software  release-05-02-19
Fork.h
1 #ifndef _Belle2_Fork_hh
2 #define _Belle2_Fork_hh
3 
4 #include <unistd.h>
5 #include <signal.h>
6 #include <sys/wait.h>
7 #include <stdlib.h>
8 
9 namespace Belle2 {
15  class Fork {
16 
17  public:
18  template <class WORKER>
19  static void g_handler_exit(int, void* worker)
20  {
21  delete(WORKER*)worker;
22  exit(0);
23  }
24  static void g_handler_int(int) { exit(0); }
25 
26  public:
27  Fork() : m_pid(-1) {}
28 
29  template<class WORKER>
30  Fork(WORKER* worker, bool detached = true)
31  {
32  m_pid = fork();
33  if (m_pid == 0) {
34  signal(SIGINT, g_handler_int);
35  if (detached) {
36  on_exit(g_handler_exit<WORKER>, (void*)worker);
37  }
38  worker->run();
39  exit(0);
40  } else if (detached) {
41  delete worker;
42  }
43  }
44  ~Fork() {}
45 
46  public:
47  pid_t get_id() const { return m_pid; }
48  void set_id(pid_t id) { m_pid = id; }
49  bool isAlive() const { return kill(0); }
50  bool kill(int signo) const
51  {
52  if (m_pid < 0) return false;
53  return ::kill(m_pid, signo) == 0;
54  }
55  bool wait(int opt = 0)
56  {
57  if (m_pid < 0) return false;
58  if (::waitpid(m_pid, NULL, opt)) {
59  m_pid = -1;
60  }
61  return true;
62  }
63  bool cancel() { return kill(SIGINT); }
64 
65  private:
66  pid_t m_pid;
67 
68  };
69 
71 }
72 
73 #endif
Belle2::Fork
Definition: Fork.h:15
Belle2
Abstract base class for different kinds of events.
Definition: MillepedeAlgorithm.h:19