You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Boost Process通过PID终止进程时,running()始终返回false且terminate()未执行的问题排查

Why does 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), waitpid can't retrieve its status, hence the error.
  • The WIFSIGNALED=1 and WTERMSIG=5 (which corresponds to SIGTRAP) results are probably misleading side effects of the waitpid error, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 16:57:37