36extern "C" char** environ;
44 std::optional<uint64_t> launch(
const std::string& executable,
45 const std::vector<std::string>& args,
46 const std::string& workingDir,
47 const std::map<std::string, std::string>& env,
48 bool detached)
override
55 std::vector<std::string> envStrings;
56 for (
char** ep = ::environ; ep && *ep; ++ep)
57 envStrings.emplace_back(*ep);
58 for (
const auto& kv : env)
60 const std::string& key = kv.first;
61 const std::string& value = kv.second;
62 std::string entry = key +
"=" + value;
71 auto it = std::find_if(envStrings.begin(), envStrings.end(),
72 [&key](
const std::string& e)
74 return e.size() > key.size() && e[key.size()] ==
'=' &&
75 e.compare(0, key.size(), key) == 0;
77 if (it != envStrings.end())
78 *it = std::move(entry);
80 envStrings.push_back(std::move(entry));
82 std::vector<char*> envp;
83 envp.reserve(envStrings.size() + 1);
84 for (
auto& s : envStrings)
85 envp.push_back(s.data());
86 envp.push_back(
nullptr);
112 pid_t inner = fork();
131 if (!workingDir.empty())
133 if (chdir(workingDir.c_str()) != 0)
142 std::vector<std::string> argStrings;
143 argStrings.reserve(args.size() + 1);
144 argStrings.push_back(executable);
145 argStrings.insert(argStrings.end(), args.begin(), args.end());
146 std::vector<char*> argv;
147 argv.reserve(argStrings.size() + 1);
148 for (
auto& s : argStrings)
150 argv.push_back(s.data());
152 argv.push_back(
nullptr);
165 DIR* fdDir = opendir(
"/proc/self/fd");
166 if (fdDir !=
nullptr)
168 int dirFd = dirfd(fdDir);
169 struct dirent* entry;
170 while ((entry = readdir(fdDir)) !=
nullptr)
172 if (entry->d_name[0] ==
'.')
177 char* endp =
nullptr;
178 long fd = std::strtol(entry->d_name, &endp, 10);
179 if (endp == entry->d_name || *endp !=
'\0')
181 if (fd > 2 && fd <= INT_MAX &&
static_cast<int>(fd) != dirFd)
183 close(
static_cast<int>(fd));
192 long maxFd = sysconf(_SC_OPEN_MAX);
197 for (
long fd = 3; fd < maxFd; ++fd)
199 close(
static_cast<int>(fd));
206 int devNull = open(
"/dev/null", O_RDWR);
209 dup2(devNull, STDIN_FILENO);
210 dup2(devNull, STDOUT_FILENO);
211 dup2(devNull, STDERR_FILENO);
217 execvpe(executable.c_str(), argv.data(), envp.data());
234 for (
int attempts = 0; attempts < 50; ++attempts)
236 pid_t r = ::waitpid(pid, &status, WNOHANG);
237 if (r == pid || r < 0)
239 std::this_thread::sleep_for(std::chrono::milliseconds(1));
241 return static_cast<uint64_t
>(pid);
245 return static_cast<uint64_t
>(pid);
249 std::optional<uint64_t> launchShell(
const std::string& command,
const std::string& workingDir,
250 bool detached)
override
252 std::vector<std::string> args = {
"-c", command};
253 return launch(
"/bin/sh", args, workingDir, {}, detached);
256 bool isRunning(uint64_t pid)
const override
259 std::filesystem::path procPath =
"/proc/" + std::to_string(pid);
260 return std::filesystem::exists(procPath);
263 std::optional<ProcessInfo> getProcessInfo(uint64_t pid)
const override
265 std::filesystem::path procPath =
"/proc/" + std::to_string(pid);
267 if (!std::filesystem::exists(procPath))
276 std::ifstream commFile(procPath /
"comm");
279 std::getline(commFile, info.name);
283 std::ifstream cmdlineFile(procPath /
"cmdline");
288 while (std::getline(cmdlineFile, arg,
'\0'))
300 std::filesystem::path exeLink = procPath /
"exe";
302 auto exePath = std::filesystem::read_symlink(exeLink, ec);
305 info.executablePath = exePath.string();
309 std::ifstream statFile(procPath /
"stat");
313 std::getline(statFile, stat);
316 auto lastParen = stat.rfind(
')');
317 if (lastParen != std::string::npos && lastParen + 2 < stat.size())
319 std::istringstream iss(stat.substr(lastParen + 2));
322 iss >> state >> ppid;
323 info.parentPid = ppid;
330 std::vector<ProcessInfo> findByName(
const std::string& name)
const override
332 std::vector<ProcessInfo> results;
334 DIR* procDir = opendir(
"/proc");
338 struct dirent* entry;
339 while ((entry = readdir(procDir)) !=
nullptr)
343 long pid = strtol(entry->d_name, &endptr, 10);
344 if (*endptr !=
'\0' || pid <= 0)
347 auto info = getProcessInfo(
static_cast<uint64_t
>(pid));
348 if (info && info->name == name)
350 results.push_back(*info);
358 std::vector<ProcessInfo> findByCommandLine(
const std::string& pattern)
const override
360 std::vector<ProcessInfo> results;
361 std::regex re(pattern, std::regex::icase);
363 DIR* procDir = opendir(
"/proc");
367 struct dirent* entry;
368 while ((entry = readdir(procDir)) !=
nullptr)
371 long pid = strtol(entry->d_name, &endptr, 10);
372 if (*endptr !=
'\0' || pid <= 0)
375 auto info = getProcessInfo(
static_cast<uint64_t
>(pid));
376 if (info && std::regex_search(info->cmdLine, re))
378 results.push_back(*info);
386 std::vector<ProcessInfo> getChildren(uint64_t parentPid)
const override
388 std::vector<ProcessInfo> results;
390 DIR* procDir = opendir(
"/proc");
394 struct dirent* entry;
395 while ((entry = readdir(procDir)) !=
nullptr)
398 long pid = strtol(entry->d_name, &endptr, 10);
399 if (*endptr !=
'\0' || pid <= 0)
402 auto info = getProcessInfo(
static_cast<uint64_t
>(pid));
403 if (info && info->parentPid == parentPid)
405 results.push_back(*info);
413 std::vector<ProcessInfo> getAllProcesses()
const override
415 std::vector<ProcessInfo> results;
417 DIR* procDir = opendir(
"/proc");
421 struct dirent* entry;
422 while ((entry = readdir(procDir)) !=
nullptr)
425 long pid = strtol(entry->d_name, &endptr, 10);
426 if (*endptr !=
'\0' || pid <= 0)
429 auto info = getProcessInfo(
static_cast<uint64_t
>(pid));
432 results.push_back(*info);
440 bool terminate(uint64_t pid,
bool force)
override
442 int sig = force ? SIGKILL : SIGTERM;
443 return kill(
static_cast<pid_t
>(pid), sig) == 0;
446 bool terminateTree(uint64_t pid)
override
449 auto children = getChildren(pid);
450 for (
const auto& child : children)
452 terminateTree(child.pid);
456 return terminate(pid,
false);
459 int waitForExit(uint64_t pid, uint32_t timeoutMs)
override
461 auto start = std::chrono::steady_clock::now();
466 pid_t result = waitpid(
static_cast<pid_t
>(pid), &status, WNOHANG);
468 if (result ==
static_cast<pid_t
>(pid))
471 if (WIFEXITED(status))
473 return WEXITSTATUS(status);
475 else if (WIFSIGNALED(status))
477 return 128 + WTERMSIG(status);
493 auto elapsed = std::chrono::steady_clock::now() - start;
494 if (std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count() >=
502 std::this_thread::sleep_for(std::chrono::milliseconds(50));
506 std::pair<int, std::string> executeAndCapture(
const std::string& command,
507 uint32_t timeoutMs)
override
517 std::array<char, 4096> buffer;
521 if (::pipe(pipefd) != 0)
524 const pid_t pid = ::fork();
536 ::dup2(pipefd[1], STDOUT_FILENO);
537 ::dup2(pipefd[1], STDERR_FILENO);
540 ::execl(
"/bin/sh",
"sh",
"-c", command.c_str(),
static_cast<char*
>(
nullptr));
547 const int fd = pipefd[0];
550 int flags = ::fcntl(fd, F_GETFL, 0);
552 ::fcntl(fd, F_SETFL, flags | O_NONBLOCK);
554 const bool hasDeadline = (timeoutMs != 0);
555 const auto deadline =
556 std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs);
557 bool timedOut =
false;
563 const auto now = std::chrono::steady_clock::now();
570 250,
static_cast<int>(
571 std::chrono::duration_cast<std::chrono::milliseconds>(deadline - now)
577 pfd.events = POLLIN | POLLHUP;
578 int pr = ::poll(&pfd, 1, waitMs);
587 ssize_t n = ::read(fd, buffer.data(), buffer.size());
590 output.append(buffer.data(),
static_cast<size_t>(n));
598 if (errno == EAGAIN || errno == EWOULDBLOCK)
609 ::kill(-pid, SIGTERM);
611 for (
int i = 0; i < 20; ++i)
614 pid_t r = ::waitpid(pid, &st, WNOHANG);
615 if (r == pid || (r < 0 && errno == ECHILD))
620 std::this_thread::sleep_for(std::chrono::milliseconds(10));
624 ::kill(-pid, SIGKILL);
626 ::waitpid(pid, &st, 0);
632 if (::waitpid(pid, &status, 0) < 0)
634 int exitCode = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
635 return {exitCode, output};
642 return std::make_unique<LinuxProcessManager>();