Belle II Software  release-05-02-19
Process.h
1 #ifndef _Belle2_Process_h
2 #define _Belle2_Process_h
3 
4 #include <unistd.h>
5 #include <signal.h>
6 #include <sys/wait.h>
7 #include <stdlib.h>
8 
9 namespace Belle2 {
15  class Process {
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  Process() : m_pid(-1) {}
28 
29  template<class WORKER>
30  Process(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  ~Process() {}
45 
46  public:
47  pid_t get_id() const { return m_pid; }
48  pid_t id() const { return m_pid; }
49  void set_id(pid_t id) { m_pid = id; }
50  bool isAlive() const { return kill(0); }
51  bool kill(int signo) const
52  {
53  if (m_pid <= 0) return false;
54  return ::kill(m_pid, signo) == 0;
55  }
56  bool wait(int opt = 0)
57  {
58  if (m_pid < 0) return false;
59  if (m_waitpid_result = ::waitpid(m_pid, &m_waitpid_status, opt)) {
60  m_pid = -1;
61  }
62  return true;
63  }
64  bool cancel() { return kill(SIGINT); }
65  int waitpid_result() const
66  {
67  return m_waitpid_result;
68  };
69  int waitpid_status() const
70  {
71  return m_waitpid_status;
72  };
73 
74  private:
75  pid_t m_pid;
76  int m_waitpid_result;
77  int m_waitpid_status;
78 
79  };
80 
82 }
83 
84 #endif
Belle2
Abstract base class for different kinds of events.
Definition: MillepedeAlgorithm.h:19
Belle2::Process
Definition: Process.h:15