game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
process_executor.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// process_executor.cpp
4// ==============================================================================
5// Implementation of centralized process execution
6// ==============================================================================
7
8#include "process_executor.h"
9#include "file_handle.h"
10#include "logger.h"
11#include "shell_utils.h"
12#include <algorithm>
13#include <cstdlib>
14#include <sstream>
15
16bool ProcessExecutor::commandLogging_ = true;
17
18// ==============================================================================
19// Simple Execution
20// ==============================================================================
21
22ProcessResult ProcessExecutor::execute(const std::string& command, bool silent)
23{
24 ProcessResult result;
25 result.command = command;
26
27 if (commandLogging_ && !silent)
28 {
29 Logger::debug("Executing: {}", command);
30 }
31
32 result.exitCode = std::system(command.c_str());
33
34 // system() returns -1 on fork/exec failure; otherwise the raw wait status.
35#ifdef __unix__
36 if (result.exitCode == -1)
37 {
38 Logger::error("[ProcessExecutor] system() failed to spawn shell for: {}", command);
39 result.success = false;
40 return result;
41 }
42 if (WIFEXITED(result.exitCode))
43 {
44 result.exitCode = WEXITSTATUS(result.exitCode);
45 }
46#endif
47
48 result.success = (result.exitCode == 0);
49
50 if (!result.success && commandLogging_ && !silent)
51 {
52 Logger::warn("Command failed with exit code {}: {}", result.exitCode, command);
53 }
54
55 return result;
56}
57
59{
60 ProcessResult result;
61
62 // Add & for background execution if not present. Guard against an empty
63 // command: back() on an empty string is undefined behaviour.
64 std::string bgCommand = command;
65 if (!bgCommand.empty() && bgCommand.find(" &") == std::string::npos && bgCommand.back() != '&')
66 {
67 bgCommand += " &";
68 }
69
70 result.command = bgCommand;
71
72 if (commandLogging_)
73 {
74 Logger::debug("Executing in background: {}", bgCommand);
75 }
76
77 result.exitCode = std::system(bgCommand.c_str());
78 // system() with a trailing & returns 0 when the shell starts the background job.
79 // -1 means the shell itself failed to start.
80 if (result.exitCode == -1)
81 {
82 result.success = false;
83 Logger::error("[ProcessExecutor] system() failed to spawn shell for background command");
84 }
85 else
86 {
87 result.success = true; // Shell launched the backgrounded process
88 }
89
90 return result;
91}
92
93// ==============================================================================
94// Execution with Output Capture
95// ==============================================================================
96
97ProcessResult ProcessExecutor::executeWithOutput(const std::string& command, bool silent)
98{
99 ProcessResult result;
100 result.command = command;
101
102 if (commandLogging_ && !silent)
103 {
104 Logger::debug("Executing with output: {}", command);
105 }
106
107 // Use PipeHandle for automatic cleanup
108 PipeHandle pipe(command, "r");
109
110 if (!pipe)
111 {
112 Logger::error("Failed to execute command: {}", command);
113 result.success = false;
114 result.exitCode = -1;
115 return result;
116 }
117
118 // Read all output (capped to prevent OOM from runaway processes)
119 std::ostringstream oss;
120 char buffer[4096];
121 constexpr size_t kMaxOutput = 10u * 1024 * 1024; // 10 MB cap
122
123 while (std::fgets(buffer, sizeof(buffer), pipe.get()) != nullptr)
124 {
125 oss << buffer;
126 if (static_cast<size_t>(oss.tellp()) > kMaxOutput)
127 break;
128 }
129
130 result.output = trimWhitespace(oss.str());
131
132 // Capture actual exit code from pclose before PipeHandle destructor runs
133 FILE* rawPipe = pipe.release();
134 if (rawPipe)
135 {
136 int status = ::pclose(rawPipe);
137#ifdef __unix__
138 if (WIFEXITED(status))
139 {
140 result.exitCode = WEXITSTATUS(status);
141 }
142 else
143 {
144 result.exitCode = status;
145 }
146#else
147 result.exitCode = status;
148#endif
149 }
150 else
151 {
152 result.exitCode = -1;
153 }
154 result.success = (result.exitCode == 0);
155
156 return result;
157}
158
159std::vector<std::string> ProcessExecutor::executeWithLines(const std::string& command,
160 size_t maxLines)
161{
162 std::vector<std::string> lines;
163
164 PipeHandle pipe(command, "r");
165 if (!pipe)
166 {
167 Logger::error("Failed to execute command: {}", command);
168 return lines;
169 }
170
171 char buffer[4096];
172 size_t lineCount = 0;
173
174 while (std::fgets(buffer, sizeof(buffer), pipe.get()) != nullptr)
175 {
176 // Remove trailing newline
177 std::string line(buffer);
178 if (!line.empty() && line.back() == '\n')
179 {
180 line.pop_back();
181 }
182
183 lines.push_back(line);
184 lineCount++;
185
186 if (maxLines > 0 && lineCount >= maxLines)
187 {
188 break;
189 }
190 }
191
192 return lines;
193}
194
195// ==============================================================================
196// Process Checking
197// ==============================================================================
198
199bool ProcessExecutor::isProcessRunning(const std::string& processName)
200{
201#ifdef _WIN32
202 std::string command = "tasklist /FI \"IMAGENAME eq " +
204 ".exe\" 2>NUL | find /I \"" +
205 ShellUtils::escapeForDoubleQuotes(processName) + ".exe\" >NUL";
206#else
207 std::string command = "pgrep -x " + ShellUtils::escapeArg(processName) + " > /dev/null 2>&1";
208#endif
209
210 ProcessResult result = execute(command, true); // Silent check
211 return result.success;
212}
213
214int ProcessExecutor::getProcessPid(const std::string& processName)
215{
216#ifdef _WIN32
217 // Windows: Use WMIC to get PID
218 std::string command = "wmic process where name=\"" +
220 ".exe\" get ProcessId /format:list 2>NUL";
221 ProcessResult result = executeWithOutput(command, true);
222
223 if (!result.success || result.output.empty())
224 {
225 return -1;
226 }
227
228 // Parse ProcessId=<pid>
229 size_t pos = result.output.find("ProcessId=");
230 if (pos != std::string::npos)
231 {
232 try
233 {
234 return std::stoi(result.output.substr(pos + 10));
235 }
236 catch (const std::exception& e)
237 {
238 Logger::warn("Failed to parse PID from wmic output: {}", e.what());
239 return -1;
240 }
241 }
242 return -1;
243#else
244 // Linux: Use pgrep
245 std::string command =
246 "pgrep -x " + ShellUtils::escapeArg(processName) + " 2>/dev/null | head -n 1";
247 ProcessResult result = executeWithOutput(command, true);
248
249 if (!result.success || result.output.empty())
250 {
251 return -1;
252 }
253
254 try
255 {
256 return std::stoi(result.output);
257 }
258 catch (const std::exception& e)
259 {
260 Logger::warn("Failed to parse PID from pgrep output: {}", e.what());
261 return -1;
262 }
263#endif
264}
265
266bool ProcessExecutor::killProcess(int pid, bool force)
267{
268 if (pid <= 0)
269 {
270 Logger::warn("Invalid PID for kill: {}", pid);
271 return false;
272 }
273
274#ifdef _WIN32
275 std::string command = force ? "taskkill /F /PID " : "taskkill /PID ";
276 command += std::to_string(pid) + " >NUL 2>&1";
277#else
278 std::string signal = force ? "SIGKILL" : "SIGTERM";
279 std::string command = "kill -" + signal + " " + std::to_string(pid) + " 2>/dev/null";
280#endif
281
282 ProcessResult result = execute(command);
283 return result.success;
284}
285
286// ==============================================================================
287// Configuration
288// ==============================================================================
289
291{
292 commandLogging_ = enabled;
293}
294
295// ==============================================================================
296// Private Helpers
297// ==============================================================================
298
299std::string ProcessExecutor::trimWhitespace(const std::string& str)
300{
301 if (str.empty())
302 {
303 return str;
304 }
305
306 size_t start = str.find_first_not_of(" \t\n\r");
307 if (start == std::string::npos)
308 {
309 return "";
310 }
311
312 size_t end = str.find_last_not_of(" \t\n\r");
313 return str.substr(start, end - start + 1);
314}
static void debug(const std::string &message, Args &&... args)
Log debug message (verbose development info).
Definition logger.h:100
static void error(const std::string &message, Args &&... args)
Log error message (recoverable failure).
Definition logger.h:124
static void warn(const std::string &message, Args &&... args)
Log warning message (non-critical issue).
Definition logger.h:116
RAII wrapper for FILE* from popen().
FILE * release()
Release ownership of FILE* without closing.
FILE * get() const
Get raw FILE* pointer.
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.
static std::string escapeArg(const std::string &arg)
Escape a string for safe use as a shell argument.
Definition shell_utils.h:65
static std::string escapeForDoubleQuotes(const std::string &arg)
Escape a string for use in double quotes.
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.