使用Boost Process通过PID终止进程时,running()始终返回false且terminate()未执行的问题排查
boost::process::child::running() always return false when attaching to an existing PID? Looks like you've hit a common pitfall with how Boost Process's child class is designed. Let's break down what's going wrong and how to fix it:
What's the issue with your current code?
When you construct a boost::process::child directly with an existing PID, you're using the class outside its intended use case. The child class is primarily meant to manage processes that Boost Process itself started, not arbitrary external processes running on the system.
The underlying waitpid failure (returning -1) is likely due to permission restrictions or mismatched process ownership:
- Unless the target process is owned by your user and in the same process group (or you have elevated privileges like
CAP_SYS_PTRACE),waitpidcan't retrieve its status, hence the error. - The
WIFSIGNALED=1andWTERMSIG=5(which corresponds toSIGTRAP) results are probably misleading side effects of thewaitpiderror, not the actual state of your target process.
How to correctly terminate an external process
Instead of forcing boost::process::child to work with an external PID, use the direct Linux system calls that are designed for this task:
1. Check if a process is running
To verify if a PID is active without sending a termination signal, use kill(pid, 0) (this just checks process existence and your permissions to interact with it):
#include <signal.h> #include <iostream> bool is_process_running(pid_t pid) { return kill(pid, 0) == 0; } // Usage: pid_t pid = 28880; std::cout << "Running: " << std::boolalpha << is_process_running(pid) << "\n";
2. Terminate the process
Use the kill() system call to send a termination signal to the PID. SIGTERM is the graceful termination signal, while SIGKILL is a forced kill (use sparingly):
#include <signal.h> #include <cstdio> pid_t pid = 28880; // Try graceful termination first if (kill(pid, SIGTERM) == -1) { perror("Failed to send SIGTERM"); // Fall back to forced kill if needed if (kill(pid, SIGKILL) == -1) { perror("Failed to send SIGKILL"); } }
If you really want to use Boost Process
While not the most straightforward approach, you can use Boost Process's native handle utilities to attach to an existing PID, but this requires careful handling of permissions and platform-specific details. For most cases, the direct kill() approach is simpler and more reliable.
内容的提问来源于stack exchange,提问作者Leon0402

