Oleg Antonyan
Oleg Antonyan

Reputation: 3113

How do I send a signal to a `Child` subprocess?

Child::kill sends a SIGKILL, but how can I send any other signal such as SIGTERM? I can probably use libc and its signal API, but is there a better way to do this?

Upvotes: 39

Views: 11745

Answers (2)

ecstaticm0rse
ecstaticm0rse

Reputation: 1566

The nix library does a good job of providing idiomatic rust wrappers around low-level UNIX operations, including sending and handling signals. In this case, you would create a nix::Pid from child_process.id(), then pass it to kill like so:

use nix::unistd::Pid;
use nix::sys::signal::{self, Signal};

// Spawn child process.
let mut child = std::process::Command::new();
/* build rest of command */
child.spawn().unwrap();

// Send SIGTERM to child process.
signal::kill(Pid::from_raw(child.id() as i32), Signal::SIGTERM).unwrap();

Upvotes: 40

StevenHe
StevenHe

Reputation: 446

Use kill

The kill command has a bunch of options to send different signals to a process. You can get the child's process id using .id().

It would be something like

let kill = Command::new("kill")
    // TODO: replace `TERM` to signal you want.
    .args(["-s", "TERM", &child.id().to_string()])
    .spawn()?;
kill.wait()?;

Upvotes: 8

Related Questions