Skip to main content

stop_child/
stop_child.rs

1//! Start a console program in its own console and stop it gracefully.
2//!
3//! ```text
4//! cargo run --example stop_child
5//! cargo run --example stop_child -- --hidden --helper path\to\terminator.exe
6//! ```
7//!
8//! The child is `ping -t` (Windows) or `sleep` (Unix), so no helper scripts
9//! are needed. On Windows the child gets its own console, which makes this
10//! the case that used to need the kamikaze proxy.
11//!
12//! Options:
13//! * `--hidden`       give the child a console without a window
14//! * `--helper <EXE>` (Windows) use another executable that links terminator
15//!   as the detached helper, as a library loaded from a DLL would have to
16
17use std::process::{Command, Stdio};
18use std::time::Duration;
19
20use terminator::{kill, stop, wait_for_stop, Method};
21
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}