DaanDeMeyer / reproc

A cross-platform (C99/C++11) process library
MIT License
552 stars 65 forks source link

Run command as sudo and forcefully close it #85

Closed vebjornjr closed 2 years ago

vebjornjr commented 2 years ago

Hello. Thank you for this library.

I'm trying to use your library to run tcpdump, which requires sudo. It seems like I'm able to run it just fine, but not able to stop it. What am I doing wrong? Thank you.

Code:

const vector<string> args = {"sudo", "tcpdump", "-i", "eth0", "udp"};
reproc::options options;
options.deadline = reproc::milliseconds(5000);
options.stop = {
    {reproc::stop::wait, reproc::deadline},                // wait until deadline
    {reproc::stop::terminate, reproc::milliseconds(500)},  // try to terminate (SIGINT) for 500ms
    {reproc::stop::kill, reproc::infinite},                // try to kill (SIGKILL) endlessly
};

const auto [status, ec] = reproc::run(args, options);
if (status == reproc::signal::terminate) {
    cout << "was terminated" << endl;
} else if (status == reproc::signal::kill) {
    cout << "was killed" << endl;
}
cout << "status = " << status << endl;
if (ec) {
    std::cerr << "Error: " << ec.message() << std::endl;
} else {
    cout << "All good!" << endl;
}

Output:

(tcpdump output) status = -1 Error: Operation not permitted

DaanDeMeyer commented 2 years ago

Your subprocess is running as root, your parent process is running as your own user, so it doesn't have permission to kill your child process.

Run your parent process with sudo instead to avoid this.

vebjornjr commented 2 years ago

I'm not so keen on running my whole program as sudo.

But I found a workaround, which was to allow tcpdump to run without sudo.

Posting it here for others that may be interested: https://askubuntu.com/questions/530920/tcpdump-permissions-problem

DaanDeMeyer commented 2 years ago

Let's close this, nothing reproc can do here really