Created
April 6, 2026 14:20
-
-
Save fritschy/337a64449627ad9e60c7c3735aa214be to your computer and use it in GitHub Desktop.
Rust std::process::Child kill on drop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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