|
16 | 16 | // For fifo's and system call |
17 | 17 | #include <cstdlib> |
18 | 18 | #include <sys/types.h> // POSIX only |
19 | | -#include <sys/stat.h> // POISX only |
| 19 | +#include <sys/stat.h> // POSIX only |
| 20 | +#include <csignal> |
| 21 | +#include <sys/wait.h> |
20 | 22 | #include <cstdio> |
21 | 23 | // For filesystem operations |
22 | 24 | #include <filesystem> |
@@ -115,14 +117,52 @@ std::string GeneratorFileOrCmd::makeCmdLine() const |
115 | 117 | return s.str(); |
116 | 118 | } |
117 | 119 | // ----------------------------------------------------------------- |
118 | | -bool GeneratorFileOrCmd::executeCmdLine(const std::string& cmd) const |
| 120 | +bool GeneratorFileOrCmd::executeCmdLine(const std::string& cmd) |
119 | 121 | { |
120 | 122 | LOG(info) << "Command line to execute: \"" << cmd << "\""; |
121 | | - int ret = std::system(cmd.c_str()); |
122 | | - if (ret != 0) { |
123 | | - LOG(fatal) << "Failed to spawn \"" << cmd << "\""; |
| 123 | + // Fork a new process |
| 124 | + pid_t pid = fork(); |
| 125 | + if (pid == -1) { |
| 126 | + LOG(fatal) << "Failed to fork process: " << std::strerror(errno); |
124 | 127 | return false; |
125 | 128 | } |
| 129 | + |
| 130 | + if (pid == 0) { |
| 131 | + // Child process |
| 132 | + setsid(); |
| 133 | + execl("/bin/sh", "sh", "-c", cmd.c_str(), (char*)nullptr); |
| 134 | + // If execl returns, there was an error, otherwise following lines will not be executed |
| 135 | + LOG(fatal) << "Failed to execute command: " << std::strerror(errno); |
| 136 | + _exit(EXIT_FAILURE); |
| 137 | + } else { |
| 138 | + // Parent process |
| 139 | + setCmdPid(pid); |
| 140 | + LOG(info) << "Child spawned process group is running with PID: " << mCmdPid; |
| 141 | + } |
| 142 | + return true; |
| 143 | +} |
| 144 | +// ----------------------------------------------------------------- |
| 145 | +bool GeneratorFileOrCmd::terminateCmd() |
| 146 | +{ |
| 147 | + if (mCmdPid == -1) { |
| 148 | + LOG(info) << "No command is currently running"; |
| 149 | + return false; |
| 150 | + } |
| 151 | + |
| 152 | + LOG(info) << "Terminating process ID group " << mCmdPid; |
| 153 | + if (kill(-mCmdPid, SIGKILL) == -1) { |
| 154 | + LOG(fatal) << "Failed to kill process: " << std::strerror(errno); |
| 155 | + return false; |
| 156 | + } |
| 157 | + |
| 158 | + // Wait for the process to terminate |
| 159 | + int status; |
| 160 | + if (waitpid(mCmdPid, &status, 0) == -1) { |
| 161 | + LOG(fatal) << "Failed to wait for process termination: " << std::strerror(errno); |
| 162 | + return false; |
| 163 | + } |
| 164 | + |
| 165 | + mCmdPid = -1; // Reset the process ID |
126 | 166 | return true; |
127 | 167 | } |
128 | 168 | // ----------------------------------------------------------------- |
|
0 commit comments