How can I guarantee that the child process will be killed if my application goes into panic?

I am writing a small test that starts the daemon process and validates it, for example:

let server = Command::new("target/debug/server").spawn();

// do some tests

server.kill();

A typical way to fail a test is panic. Unfortunately, this means that kill () is never called, and repeated runs of the test suite are not executed, because the port is being executed by an old process that is still running.

Is there something like a TRAP function that I can use to ensure that the Baby is killed?

+4
source share
2 answers

- catch_panic. catch_panic , scoped spawn ed thread join ing. Ok(ClosureRetVal) Err(Box<Any>), .

let res = std::thread::catch_panic(|| {
    panic!("blub: {}", 35);
});
if let Err(err) = res {
    let msg: String = *err.downcast().unwrap();
    println!("{}", msg);
}

PlayPen

+4

RAII, , , . , , std:: thread:: panicking.

use std::process::{Command,Child};

struct ChildGuard(Child);

impl Drop for ChildGuard {
    fn drop(&mut self) {
        // You can check std::thread::panicking() here
        match self.0.kill() {
            Err(e) => println!("Could not kill child process: {}", e),
            Ok(_) => println!("Successfully killed child process"),
        }
    }
}

fn main() {
    let child = Command::new("/bin/cat").spawn().unwrap();
    let _guard = ChildGuard(child);

    panic!("Main thread panicking");
}
+3

All Articles