From c895a1dc59ff607179b5cebd7b69ef24eb34ca8f Mon Sep 17 00:00:00 2001 From: TheAssassin Date: Fri, 7 Aug 2020 15:32:07 +0200 Subject: [PATCH] Add kill and poll features for processes --- include/linuxdeploy/subprocess/process.h | 15 ++++++++++++++- src/subprocess/process.cpp | 23 +++++++++++++++++++++-- 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/include/linuxdeploy/subprocess/process.h b/include/linuxdeploy/subprocess/process.h index fbc903e..65a1eaa 100644 --- a/include/linuxdeploy/subprocess/process.h +++ b/include/linuxdeploy/subprocess/process.h @@ -1,6 +1,7 @@ // system headers #include #include +#include // local headers #include "linuxdeploy/subprocess/subprocess.h" @@ -62,10 +63,22 @@ namespace linuxdeploy { int stderr_fd() const; /** - * Close all pipes and wait for process to exit. If process was closed already, just returns exit code. + * Close all pipes and wait for process to exit. + * If process is not running any more, just returns exit code. * @return child process's exit code */ int close(); + + /** + * Kill underlying process with given signal. By default, SIGTERM is used to end the process. + */ + void kill(int signal = SIGTERM) const; + + /** + * Check whether process is still alive. Use close() to fetch exit code. + * @return true while process is alive, false otherwise + */ + bool poll(); }; } } diff --git a/src/subprocess/process.cpp b/src/subprocess/process.cpp index 459af62..2a3e5c9 100644 --- a/src/subprocess/process.cpp +++ b/src/subprocess/process.cpp @@ -54,8 +54,6 @@ process::process(const std::vector& args, const subprocess_env_map_ throw std::runtime_error{"fork() failed"}; } - std::cout << "child pid: " << std::to_string(child_pid_) << std::endl; - if (child_pid_ == 0) { // we're in the child process @@ -190,3 +188,24 @@ std::vector process::make_env_vector_(const subprocess_env_map_t& env) { return rv; } + +void process::kill(int signal) const { + if (::kill(child_pid_, signal) != 0) { + throw std::logic_error{"failed to kill child process"}; + } +} + +bool process::poll() { + if (exited_) { + return false; + } + + int temporary; + + if (waitpid(child_pid_, &temporary, WNOHANG) != 0) { + return true; + } + + exit_code_ = WEXITSTATUS(temporary); + return false; +}