Belle II Software  release-08-01-10
Process.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_Process_h
9 #define _Belle2_Process_h
10 
11 #include <unistd.h>
12 #include <signal.h>
13 #include <sys/wait.h>
14 #include <stdlib.h>
15 
16 namespace Belle2 {
22  class Process {
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  Process() : m_pid(-1) {}
35 
36  template<class WORKER>
37  Process(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  ~Process() {}
52 
53  public:
54  pid_t get_id() const { return m_pid; }
55  pid_t id() const { return m_pid; }
56  void set_id(pid_t id) { m_pid = id; }
57  bool isAlive() const { return kill(0); }
58  bool kill(int signo) const
59  {
60  if (m_pid <= 0) return false;
61  return ::kill(m_pid, signo) == 0;
62  }
63  bool wait(int opt = 0)
64  {
65  if (m_pid < 0) return false;
66  if ((m_waitpid_result = ::waitpid(m_pid, &m_waitpid_status, opt))) {
67  m_pid = -1;
68  }
69  return true;
70  }
71  bool cancel() { return kill(SIGINT); }
72  int waitpid_result() const
73  {
74  return m_waitpid_result;
75  };
76  int waitpid_status() const
77  {
78  return m_waitpid_status;
79  };
80 
81  private:
82  pid_t m_pid;
83  int m_waitpid_result;
84  int m_waitpid_status;
85 
86  };
87 
89 }
90 
91 #endif
Abstract base class for different kinds of events.