Leon0402
Leon0402

Reputation: 298

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?

Upvotes: 1

Views: 2460

Answers (1)

sehe
sehe

Reputation: 393497

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 e.g.

cat &
./sotest $!

Prints

enter image description here

Upvotes: 2

Related Questions