Skip to main content

kill

Function kill 

Source
pub fn kill(pid: u32) -> Result<()>
Expand description

Forcibly terminate the process with id pid.

Windows: TerminateProcess. POSIX: SIGKILL. The process gets no chance to clean up; prefer stop when a graceful shutdown is possible.

Examples found in repository?
examples/stop_child.rs (line 83)
22fn main() {
23    let mut hidden = false;
24    let mut helper: Option<String> = None;
25    let mut args = std::env::args().skip(1);
26    while let Some(arg) = args.next() {
27        match arg.as_str() {
28            "--hidden" => hidden = true,
29            "--helper" => helper = args.next(),
30            other => {
31                eprintln!("unknown argument '{other}'");
32                std::process::exit(2);
33            }
34        }
35    }
36
37    #[cfg(windows)]
38    if let Some(path) = &helper {
39        terminator::set_helper(terminator::Helper::Path(path.into()));
40    }
41    #[cfg(not(windows))]
42    let _ = (hidden, &helper);
43
44    // Whoever started this demo may have disabled Ctrl+C (CREATE_NEW_PROCESS_GROUP, or a shell
45    // that called SetConsoleCtrlHandler(NULL, TRUE)). That state is inherited, so `ping` would
46    // ignore the event we are about to send. Make sure the child starts with normal handling.
47    #[cfg(windows)]
48    // SAFETY: plain call, no pointers; (NULL, FALSE) restores the default handling.
49    unsafe {
50        windows_sys::Win32::System::Console::SetConsoleCtrlHandler(None, 0);
51    }
52
53    let mut cmd;
54    #[cfg(windows)]
55    {
56        use std::os::windows::process::CommandExt;
57        const CREATE_NEW_CONSOLE: u32 = 0x0000_0010;
58        const CREATE_NO_WINDOW: u32 = 0x0800_0000;
59        cmd = Command::new("ping");
60        cmd.args(["-t", "127.0.0.1"]).creation_flags(if hidden {
61            CREATE_NO_WINDOW
62        } else {
63            CREATE_NEW_CONSOLE
64        });
65    }
66    #[cfg(not(windows))]
67    {
68        cmd = Command::new("sleep");
69        cmd.arg("1000");
70    }
71    let mut child = cmd
72        .stdin(Stdio::null())
73        .stdout(Stdio::null())
74        .stderr(Stdio::null())
75        .spawn()
76        .expect("cannot start the child");
77    let pid = child.id();
78    println!("started {pid}");
79    std::thread::sleep(Duration::from_millis(500));
80
81    if let Err(e) = stop(pid, Method::CtrlC) {
82        eprintln!("cannot stop {pid}: {e}");
83        let _ = kill(pid);
84        let _ = child.wait();
85        std::process::exit(1);
86    }
87    println!("Ctrl+C delivered to {pid}");
88
89    if wait_for_stop(pid, Some(Duration::from_secs(5))) {
90        println!("{pid} exited gracefully");
91    } else {
92        println!("{pid} ignored Ctrl+C, killing it");
93        let _ = kill(pid);
94    }
95    let _ = child.wait();
96}