简体   繁体   中英

Kill process by pid with boost process

I do want to kill a process I have a pid of, so my code is the following:

pid_t pid = 28880;
boost::process::child process { pid };
std::cout << "Running: " << process.running() << "\n";
process.terminate();

I noticed though that running() always returns false (no matter what pid I take) and based on the source code then terminate isn't even called.

Digging a little bit deeper it seem to be the linux function waitpid is called. And it always returns -1 (which means some error has occured, rather than 0, which would mean: Yes the process is still running).

WIFSIGNALED return 1 and WTERMSIG returns 5.

Am I doing something wrong here?

Boost process is a library for the execution (and manipulation) of child processes. Yours is not (necesarily) a child process, and not created by boost.

Indeed running() doesn't work unless the process is attached. Using that constructor by definition results in a detached process.

This leaves the interesting question why this constructor exists, but let's focus on the question.

Detached processes cannot be joined or terminated.

The terminate() call is a no-op.

I would suggest writing the logic yourself - the code is not that complicated (POSIX kill or TerminateProcess ).

If you want you can cheat by using implementation details from the library:

#include <boost/process.hpp>
#include <iostream>
namespace bp = boost::process;

int main(int argc, char** argv) {
    for (std::string_view arg : std::vector(argv + 1, argv + argc)) {
        bp::child::child_handle pid{std::atoi(arg.data())};
        std::cout << "pid " << pid.id();

        std::error_code ec;
        bp::detail::api::terminate(pid, ec);
        std::cout << " killed: " << ec.message() << std::endl;
    }
}

With eg

cat &
./sotest $!

Prints

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM