Skip to content

Instantly share code, notes, and snippets.

@fritschy
Created April 6, 2026 14:20
Show Gist options
  • Select an option

  • Save fritschy/337a64449627ad9e60c7c3735aa214be to your computer and use it in GitHub Desktop.

Select an option

Save fritschy/337a64449627ad9e60c7c3735aa214be to your computer and use it in GitHub Desktop.
Rust std::process::Child kill on drop
use std::{
ops::{Deref, DerefMut},
process::{Child, Command},
};
struct KillOnDrop(Child);
impl Drop for KillOnDrop {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
impl Deref for KillOnDrop {
type Target = Child;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for KillOnDrop {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
fn main() {
let sleep = Command::new("sleep")
.arg("1000")
.spawn()
.map(KillOnDrop)
.unwrap();
println!("sleep: {}", sleep.id());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment