terminator/lib.rs
1//! Stop processes gracefully, even on Windows.
2//!
3//! On Windows this sends real `CTRL_C_EVENT` / `CTRL_BREAK_EVENT` console
4//! signals (or closes a GUI window) to an arbitrary process, and can write to
5//! its standard input. Unlike the original Go implementation it does not ship
6//! and drop a separate "proxy" executable into a temporary folder.
7//!
8//! Windows can attach a process to only one console at a time, so reaching a
9//! foreign console sometimes needs a short-lived detached process. The crate
10//! picks the cheapest route automatically:
11//!
12//! 1. **Direct**: the target shares the caller's console, nothing to attach.
13//! 2. **In-process**: the caller has no console, so attach, send, detach.
14//! 3. **Helper**: the caller has its own console; a detached helper attaches
15//! to the target console instead. By default the helper is *the current
16//! executable re-launched with a marker argument*, intercepted before
17//! `main` by a C runtime initializer that this crate registers itself. No
18//! call from `main` is needed ([`run_helper_if_requested`] exists only for
19//! unusual setups). When this code lives in a DLL, point the crate to an
20//! executable that links it with [`set_helper`].
21//!
22//! On Unix it sends POSIX signals and can write to a process' controlling TTY.
23//!
24//! Set `TERMINATOR_DEBUG=1` to print the chosen route to stderr.
25//!
26//! # Quick start
27//!
28//! ```no_run
29//! use terminator::{stop, Method};
30//! # fn main() -> terminator::Result<()> {
31//! stop(1234, Method::CtrlC)?;
32//! # Ok(())
33//! # }
34//! ```
35
36mod error;
37mod tree;
38
39pub use error::{Error, Result};
40pub use tree::child_tree;
41
42use std::time::{Duration, Instant};
43
44#[cfg_attr(windows, path = "platform/windows.rs")]
45#[cfg_attr(unix, path = "platform/posix.rs")]
46mod platform;
47
48#[cfg(windows)]
49pub use platform::{
50 close_window, main_window, run_helper_if_requested, set_helper, Helper, WindowHandle,
51};
52
53/// Does nothing on this platform. Exists so cross-platform code can call it
54/// unconditionally; see the Windows documentation for the real behavior.
55#[cfg(unix)]
56pub fn run_helper_if_requested() {}
57
58/// A cross-platform way to ask a process to stop.
59///
60/// POSIX has no equivalent of the Windows console control events or window
61/// messages, so there every method sends `SIGINT`.
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub enum Method {
64 /// Windows: `CTRL_C_EVENT` to the target console. POSIX: `SIGINT`.
65 ///
66 /// Reaches every process attached to that console which has not disabled
67 /// Ctrl+C handling.
68 CtrlC,
69 /// Windows: `CTRL_BREAK_EVENT` to the target console. POSIX: `SIGINT`.
70 ///
71 /// Unlike Ctrl+C it cannot be disabled with `SetConsoleCtrlHandler(NULL,
72 /// TRUE)`, so it is more reliable for processes that masked Ctrl+C.
73 CtrlBreak,
74 /// Windows: posts `WM_CLOSE` to the main GUI window of the process; for a packaged (UWP)
75 /// app, to the frame window that hosts it. POSIX: `SIGINT`.
76 CloseWindow,
77}
78
79/// Ask the process with id `pid` to stop using the given [`Method`].
80///
81/// Returns `Ok(())` once the request was delivered. Delivery does not
82/// guarantee the process handled it or exited; use [`wait_for_stop`].
83pub fn stop(pid: u32, method: Method) -> Result<()> {
84 platform::stop(pid, method)
85}
86
87/// Forcibly terminate the process with id `pid`.
88///
89/// Windows: `TerminateProcess`. POSIX: `SIGKILL`. The process gets no chance
90/// to clean up; prefer [`stop`] when a graceful shutdown is possible.
91pub fn kill(pid: u32) -> Result<()> {
92 platform::kill(pid)
93}
94
95/// Write `msg` to the standard input of the process with id `pid`.
96///
97/// Useful to answer prompts such as `Terminate batch job (Y/N)?`.
98///
99/// On Windows the message is injected into the target console's input buffer
100/// and must end with `"\r\n"` to be submitted. On Unix it is pushed into the
101/// process' controlling terminal with `TIOCSTI`, which usually requires root
102/// (and is disabled by some kernels); use `"\n"` on Linux, `"\r"` on macOS.
103pub fn send_message(pid: u32, msg: &str) -> Result<()> {
104 platform::send_message(pid, msg)
105}
106
107/// Returns `true` while the process with id `pid` is running.
108pub fn is_running(pid: u32) -> bool {
109 platform::is_running(pid)
110}
111
112/// Block until the process `pid` is no longer running or `timeout` elapses
113/// (forever if `None`). Returns `true` if the process stopped.
114pub fn wait_for_stop(pid: u32, timeout: Option<Duration>) -> bool {
115 let start = Instant::now();
116 loop {
117 if !platform::is_running(pid) {
118 return true;
119 }
120 if let Some(t) = timeout {
121 if start.elapsed() >= t {
122 return false;
123 }
124 }
125 std::thread::sleep(Duration::from_millis(25));
126 }
127}