rust - Kill child process while waiting for it -
i want execute process , want wait until has finished. lets spawn , wait process in thread t1:
let child = command::new("rustc").spawn().unwrap(); child.wait();
now, if special event occurs (which thread t0 waiting for) want kill spawned process:
if let ok(event) = special_event_notifier.recv() { child.kill(); }
but don't see way it: both kill
, wait
take mutable reference child
, therefore mutually exclusive. after calling wait
no 1 can have reference child
anymore.
i've found wait-timeout
crate, want know if there's way.
obviously, can kill process yourself. child::id
method gives "os-assigned process identifier" should sufficient that.
the problem killing process platform-dependent action. on unix killing process handled kill function:
#![feature(libc)] extern crate libc; use std::env::args; use std::process::command; use std::thread::{spawn, sleep}; use std::time::duration; use libc::{kill, sigterm}; fn main() { let mut child = command::new("/bin/sh").arg("-c").arg("sleep 1; echo foo").spawn().unwrap(); let child_id = child.id(); if args().any(|arg| arg == "--kill") { spawn(move || { sleep(duration::from_millis(100)); unsafe { kill(child_id i32, sigterm); } }); } child.wait().unwrap(); }
on windows might try openprocess , terminateprocess functions (available kernel32-sys crate).
Comments
Post a Comment