SlHelpers
Process.h
1 // SPDX-License-Identifier: GPL-2.0-only
2 
3 #pragma once
4 
5 #include <filesystem>
6 #include <string>
7 #include <vector>
8 
9 #include <sys/types.h>
10 
11 namespace SlHelpers {
12 
16 class Process {
17 public:
19  enum Error {
20  UnknownError,
21  BusyError,
22  PipeError,
23  SpawnError,
24  WaitPidError,
25  ReadError,
26  WriteError,
27  };
28 
29  Process() : m_pid(-1), m_pipe{-1, -1}, m_signalled(false), m_exitStatus(0), m_lastError(""),
30  m_lastErrorNo(UnknownError) {}
31  ~Process();
32 
43  bool run(const std::filesystem::path &program, const std::vector<std::string> &args = {},
44  std::string *out = nullptr);
45 
53  bool spawn(const std::filesystem::path &program, const std::vector<std::string> &args = {},
54  bool captureStdout = false);
55 
61  bool readAll(std::string &out);
62 
67  int readPipe() const { return m_pipe[0]; }
68 
73  bool waitForFinished();
74 
76  bool kill(int sig);
77 
82  pid_t pid() const { return m_pid; }
83 
88  bool signalled() const { return m_signalled; }
89 
94  unsigned int exitStatus() const { return m_exitStatus; }
95 
97  const std::string &lastError() const { return m_lastError; }
99  Error lastErrorNo() const { return m_lastErrorNo; }
100 private:
101  void closePipe(const unsigned int &p);
102  void setError(const Error &errNo, const std::string &error) {
103  m_lastErrorNo = errNo;
104  m_lastError = error;
105  }
106 
107  pid_t m_pid;
108  int m_pipe[2];
109  bool m_signalled;
110  unsigned int m_exitStatus;
111  std::string m_lastError;
112  Error m_lastErrorNo;
113 };
114 
115 }
pid_t pid() const
Return the process ID for the child process.
Definition: Process.h:82
Error
Errors returned by lastErrorNo()
Definition: Process.h:19
int readPipe() const
Get the stdout pipe of the process.
Definition: Process.h:67
bool spawn(const std::filesystem::path &program, const std::vector< std::string > &args={}, bool captureStdout=false)
Forks a process and executes program with args.
bool run(const std::filesystem::path &program, const std::vector< std::string > &args={}, std::string *out=nullptr)
Spawns a process, executes program with args, and waits for its termination.
Creates a process and executes a program.
Definition: Process.h:16
unsigned int exitStatus() const
Exit status of the children (aka WEXITSTATUS())
Definition: Process.h:94
bool kill(int sig)
Send a signal sig to the process.
bool waitForFinished()
Wait until the underlying process is finished (or dead)
bool readAll(std::string &out)
Read everything from process&#39; stdout.
const std::string & lastError() const
Return the last error string if some.
Definition: Process.h:97
bool signalled() const
Was the child signalled?
Definition: Process.h:88
Error lastErrorNo() const
Return the last error number.
Definition: Process.h:99
Definition: Color.h:8