Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 939
Oleg Antonyan Avatar asked Mar 10 '18 15:03

Oleg Antonyan


People also ask

How do you send signals to the child process?

fork() creates the child process from the parent. The pid can be checked to decide whether it is the child (if pid == 0) or the parent (pid = child process id). The parent can then send messages to child using the pid and kill(). The child picks up these signals with signal() and calls appropriate functions.

Do children inherit signal handlers?

a child process inherits signal settings from its parent during fork (). When process performs exec (), previously ignored signals remain ignored but installed handlers are set back to the default handler.

Does Sigterm propagate to child processes?

There is no automatic propagation of signals (SIGTERM or otherwise) to children in the process tree.

Is subprocess a child process?

A child process in computing is a process created by another process (the parent process). This technique pertains to multitasking operating systems, and is sometimes called a subprocess or traditionally a subtask.


1 Answers

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()), Signal::SIGTERM).unwrap();
like image 99
ecstaticm0rse Avatar answered Sep 19 '22 17:09

ecstaticm0rse