Skip to content

Commit

Permalink
passthrough signal to child process
Browse files Browse the repository at this point in the history
Signed-off-by: Yang Keao <[email protected]>
  • Loading branch information
YangKeao committed Dec 8, 2020
1 parent b9d8356 commit eaa2bf2
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 3 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "nsexec"
version = "0.1.4"
version = "0.1.5"
authors = ["Yang Keao <[email protected]>"]
edition = "2018"

Expand Down
23 changes: 22 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ use structopt::StructOpt;
use nix::sched::{CloneFlags, setns};
use nix::fcntl::{open, OFlag};
use nix::sys::stat::Mode;
use nix::sys::signal::{signal, SigHandler, Signal, kill};
use nix::unistd::Pid;

use std::process::Command;
use std::path::PathBuf;
use std::os::unix::process::CommandExt;
use std::cell::RefCell;

#[derive(StructOpt, Debug)]
#[structopt(
Expand Down Expand Up @@ -41,7 +43,22 @@ struct Opt {
pub cmd: Vec<String>
}

thread_local! {
static CHILD_PID: RefCell<Option<u32>> = RefCell::new(None)
}

extern "C" fn signal_handler(_: libc::c_int) {
CHILD_PID.with(|pid| {
if let Some(pid) = *pid.borrow_mut() {
kill(Pid::from_raw(pid as i32), Signal::SIGTERM).unwrap();
}
});
}

fn main() {
unsafe { signal(Signal::SIGINT, SigHandler::Handler(signal_handler)).unwrap() };
unsafe { signal(Signal::SIGTERM, SigHandler::Handler(signal_handler)).unwrap() };

let opts = Opt::from_args();

if let Some(cgroup) = opts.cgroup {
Expand Down Expand Up @@ -89,6 +106,10 @@ fn main() {
};

let mut child = command.spawn().unwrap();
let pid = child.id();
CHILD_PID.with(move |p| {
*p.borrow_mut() = Some(pid);
});
let status = child.wait().unwrap();

if let Some(code) = status.code() {
Expand Down

0 comments on commit eaa2bf2

Please sign in to comment.