game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
process_executor.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// process_executor.h
4// ==============================================================================
5// Centralized process execution with error handling and logging
6// ==============================================================================
7// This replaces direct system() and popen() calls throughout the codebase
8// with a centralized, error-handling abstraction that:
9// - Checks return codes
10// - Logs commands and errors
11// - Provides timeout support
12// - Returns structured results
13//
14// ## Usage Example
15// @code
16// // Simple command execution
17// ProcessResult result = ProcessExecutor::execute("ls -l");
18// if (result.success) {
19// Logger::info("Command succeeded with exit code: {}", result.exitCode);
20// }
21//
22// // Command with output capture
23// ProcessResult result = ProcessExecutor::executeWithOutput("pgrep -x steam");
24// if (result.success && !result.output.empty()) {
25// Logger::info("Steam is running: {}", result.output);
26// }
27//
28// // Silent background command
29// ProcessExecutor::executeBackground("steam -silent");
30// @endcode
31// ==============================================================================
32
33#pragma once
34
35#include <string>
36#include <vector>
37
38// ==============================================================================
39// ProcessResult - Result of command execution
40// ==============================================================================
41
42/**
43 * @struct ProcessResult
44 * @brief Result of process execution including exit code and output
45 */
47{
48 bool success; ///< true if command executed successfully (exit code 0)
49 int exitCode; ///< Process exit code (0 = success)
50 std::string output; ///< Captured stdout (if requested)
51 std::string command; ///< The command that was executed
52
53 ProcessResult() : success(false), exitCode(-1) {}
54};
55
56// ==============================================================================
57// ProcessExecutor - Static utility class for process execution
58// ==============================================================================
59
60/**
61 * @class ProcessExecutor
62 * @brief Centralized process execution with error handling and logging
63 *
64 * All methods are static for convenient usage without instantiation.
65 * Provides consistent error handling across all command executions.
66 */
67class ProcessExecutor
68{
69 public:
70 // ==========================================================================
71 // Simple Execution (no output capture)
72 // ==========================================================================
73
74 /**
75 * @brief Execute command and check exit code
76 * @param command Shell command to execute
77 * @param silent If true, suppress command logging (for frequent operations)
78 * @return ProcessResult with success flag and exit code
79 *
80 * Uses system() internally. Command runs through shell.
81 * stdout/stderr are not captured (go to console).
82 */
83 static ProcessResult execute(const std::string& command, bool silent = false);
84
85 /**
86 * @brief Execute command in background (non-blocking)
87 * @param command Shell command to execute
88 * @return ProcessResult (success indicates launch, not completion)
89 *
90 * Appends " &" to command if not present.
91 * Returns immediately without waiting for completion.
92 */
93 static ProcessResult executeBackground(const std::string& command);
94
95 // ==========================================================================
96 // Execution with Output Capture
97 // ==========================================================================
98
99 /**
100 * @brief Execute command and capture stdout
101 * @param command Shell command to execute
102 * @param silent If true, suppress command logging
103 * @return ProcessResult with output captured in result.output
104 *
105 * Uses popen() internally. stderr is redirected to /dev/null.
106 * Output is trimmed of trailing whitespace.
107 */
108 static ProcessResult executeWithOutput(const std::string& command, bool silent = false);
109
110 /**
111 * @brief Execute command and capture stdout as lines
112 * @param command Shell command to execute
113 * @param maxLines Maximum lines to read (0 = unlimited)
114 * @return Vector of output lines
115 *
116 * Useful for parsing multi-line command output.
117 * Empty lines are preserved.
118 */
119 static std::vector<std::string> executeWithLines(const std::string& command,
120 size_t maxLines = 0);
121
122 // ==========================================================================
123 // Process Checking
124 // ==========================================================================
125
126 /**
127 * @brief Check if process is running by name
128 * @param processName Name of process to check (e.g., "steam")
129 * @return true if process is running
130 *
131 * Uses pgrep on Linux, tasklist on Windows.
132 */
133 static bool isProcessRunning(const std::string& processName);
134
135 /**
136 * @brief Get PID of running process by name
137 * @param processName Name of process to check
138 * @return PID if found, -1 otherwise
139 *
140 * If multiple processes match, returns first PID found.
141 */
142 static int getProcessPid(const std::string& processName);
143
144 /**
145 * @brief Kill process by PID
146 * @param pid Process ID to kill
147 * @param force If true, use SIGKILL instead of SIGTERM
148 * @return true if kill signal was sent successfully
149 */
150 static bool killProcess(int pid, bool force = false);
151
152 // ==========================================================================
153 // Configuration
154 // ==========================================================================
155
156 /**
157 * @brief Enable or disable command logging
158 * @param enabled If true, log all commands before execution
159 *
160 * Default: enabled
161 * Useful to disable for very frequent operations.
162 */
163 static void setCommandLogging(bool enabled);
164
165 private:
166 ProcessExecutor() = delete; // Static class, no instantiation
167
168 static std::string trimWhitespace(const std::string& str);
169 static bool commandLogging_;
170};
static ProcessResult executeWithOutput(const std::string &command, bool silent=false)
Execute command and capture stdout.
static bool killProcess(int pid, bool force=false)
Kill process by PID.
static void setCommandLogging(bool enabled)
Enable or disable command logging.
static ProcessResult executeBackground(const std::string &command)
Execute command in background (non-blocking).
static ProcessResult execute(const std::string &command, bool silent=false)
Execute command and check exit code.
static bool isProcessRunning(const std::string &processName)
Check if process is running by name.
static int getProcessPid(const std::string &processName)
Get PID of running process by name.
static std::vector< std::string > executeWithLines(const std::string &command, size_t maxLines=0)
Execute command and capture stdout as lines.
Result of process execution including exit code and output.
int exitCode
Process exit code (0 = success).
bool success
true if command executed successfully (exit code 0)
std::string output
Captured stdout (if requested).
std::string command
The command that was executed.