Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

rust - Kill child process while waiting for it

I want to execute another process and normally want to wait until it has finished. Lets say we spawn and wait for the process in thread T1:

let child = Command::new("rustc").spawn().unwrap();
child.wait();

Now, if a special event occurs (which thread T0 is waiting for) I want to kill the spawned process:

if let Ok(event) = special_event_notifier.recv() {
    child.kill();
}

But I don't see a way to do it: both kill and wait take a mutable reference to Child and are therefore mutually exclusive. After calling wait no one can have any reference to child anymore.

I've found the wait-timeout crate, but I want to know if there's another way.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Obviously, you can just kill the process yourself. The Child::id method gives you the "OS-assigned process identifier" that should be sufficient for that.

The only problem is that killing a process is a platform-dependent action. On UNIX killing a process is handled with the 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 as i32, SIGTERM);
            }
        });
    }
    child.wait().unwrap();
}

On Windows you might try the OpenProcess and TerminateProcess functions (available with the kernel32-sys crate).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...