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.
If the child subprocess do not close stdout before finishing, it's possible to wait reading stdout. Here is an example
The output of this program on my system is
Although not in the docs, killing a finished child returns
Ok
.This works because killing a process close the files associated with it. However, if the child spawn new processes, killing the child may not kill these other processes and they may keep the stdout opened.
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:
On Windows you might try the OpenProcess and TerminateProcess functions (available with the kernel32-sys crate).