SlHelpers
Loading...
Searching...
No Matches
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
11namespace SlHelpers {
12
16class Process {
17public:
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
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; }
100private:
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}
Creates a process and executes a program.
Definition Process.h:16
Error lastErrorNo() const
Return the last error number.
Definition Process.h:99
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.
bool spawn(const std::filesystem::path &program, const std::vector< std::string > &args={}, bool captureStdout=false)
Forks a process and executes program with args.
pid_t pid() const
Return the process ID for the child process.
Definition Process.h:82
unsigned int exitStatus() const
Exit status of the children (aka WEXITSTATUS()).
Definition Process.h:94
bool readAll(std::string &out)
Read everything from process' stdout.
bool signalled() const
Was the child signalled?
Definition Process.h:88
bool waitForFinished()
Wait until the underlying process is finished (or dead).
const std::string & lastError() const
Return the last error string if some.
Definition Process.h:97
int readPipe() const
Get the stdout pipe of the process.
Definition Process.h:67
bool kill(int sig)
Send a signal sig to the process.
Error
Errors returned by lastErrorNo().
Definition Process.h:19