Belle II Software development
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
16namespace Belle2 {
21
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 explicit Process(WORKER* worker, bool detached = true) : m_pid(fork())
38 {
39 if (m_pid == 0) {
40 signal(SIGINT, g_handler_int);
41 if (detached) {
42 on_exit(g_handler_exit<WORKER>, static_cast<void*>(worker));
43 }
44 worker->run();
45 exit(0);
46 } else if (detached) {
47 delete worker;
48 }
49 }
50 ~Process() {}
51
52 public:
53 pid_t get_id() const { return m_pid; }
54 pid_t 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 ((m_waitpid_result = ::waitpid(m_pid, &m_waitpid_status, opt))) {
66 m_pid = -1;
67 }
68 return true;
69 }
70 bool cancel() { return kill(SIGINT); }
71 int waitpid_result() const
72 {
73 return m_waitpid_result;
74 };
75 int waitpid_status() const
76 {
77 return m_waitpid_status;
78 };
79
80 private:
81 pid_t m_pid;
82 int m_waitpid_result = 0;
83 int m_waitpid_status = 0;
84
85 };
86
88}
89
90#endif
Abstract base class for different kinds of events.