Elaboradar  0.1
subprocess.h
1 #ifndef RADARELAB_UTILS_SUBPROCESS_H
2 #define RADARELAB_UTILS_SUBPROCESS_H
3 
4 #include <vector>
5 #include <string>
6 #include <sys/types.h>
7 
8 namespace radarelab {
9 namespace utils {
10 namespace subprocess {
11 
12 enum class Redirect
13 {
17  PIPE,
18 
20  DEVNULL,
21 
23  STDOUT,
24 
26  FD,
27 
29  UNCHANGED,
30 };
31 
32 
33 class Child
34 {
35 protected:
36  pid_t m_pid = 0;
37  int m_returncode = 0;
38  bool m_terminated = false;
39  int m_stdin[2] = { -1, -1 };
40  int m_stdout[2] = { -1, -1 };
41  int m_stderr[2] = { -1, -1 };
42  Redirect m_stdin_action = Redirect::UNCHANGED;
43  Redirect m_stdout_action = Redirect::UNCHANGED;
44  Redirect m_stderr_action = Redirect::UNCHANGED;
45 
47  virtual void pre_fork();
48 
50  virtual void post_fork_parent();
51 
53  virtual void post_fork_child();
54 
60  virtual int main() noexcept = 0;
61 
62 public:
64  bool close_fds = true;
65 
70  std::vector<int> pass_fds;
71 
73  std::string cwd;
74 
76  bool start_new_session = false;
77 
79  int get_stdin() const;
81  int get_stdout() const;
83  int get_stderr() const;
84 
86  void set_stdin(int fd);
88  void set_stdin(Redirect val);
90  void set_stdout(int fd);
92  void set_stdout(Redirect val);
94  void set_stderr(int fd);
96  void set_stderr(Redirect val);
97 
99  void close_stdin();
101  void close_stdout();
103  void close_stderr();
104 
105  Child() = default;
106  Child(const Child&) = delete;
107  Child(Child&&) = delete;
108  virtual ~Child();
109 
110  Child& operator=(const Child&) = delete;
111  Child& operator=(Child&&) = delete;
112 
114  void fork();
115 
117  pid_t pid() const { return m_pid; }
118 
123  int returncode() const;
124 
126  int raw_returncode() const { return m_returncode; }
127 
129  bool started() const { return m_pid != 0; }
130 
132  bool terminated() const { return m_terminated; }
133 
135  bool poll();
136 
138  int wait();
139 
141  void send_signal(int sig);
142 
144  void terminate();
145 
147  void kill();
148 
150  static std::string format_raw_returncode(int raw_returncode);
151 };
152 
153 
154 class Popen : public Child
155 {
156 protected:
157  int main() noexcept override;
158 
159 public:
161  std::vector<std::string> args;
163  std::string executable;
165  std::vector<std::string> env;
166 
167  using Child::Child;
168 
169  Popen() = default;
170  Popen(std::initializer_list<std::string> args);
171 
173  void copy_env_from_parent();
174 
175  void setenv(const std::string& key, const std::string& val);
176 };
177 
178 
179 }
180 }
181 }
182 
183 #endif
String functions.
Definition: cart.cpp:4