running-process 4.6.2

Subprocess and PTY runtime for the running-process project
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Two-mode process spawning. Free functions only — no module-internal traits.
//!
//! Modes (only two; the dangerous combination `detached + caller-pipes` has no
//! API surface):
//!
//!   * [`spawn_daemon`] — detached lifetime, NUL stdio, sanitized handle list,
//!     no console window, ignores parent's Ctrl-C. The returned [`DaemonChild`]
//!     does NOT die when dropped.
//!   * [`spawn`] — contained lifetime, caller-controlled stdio via
//!     [`SpawnStdio`], sanitized handle list, no console window by default
//!     (opt in via [`SpawnStdio::show_console`]), bounded drain. The returned
//!     [`SpawnedChild`] kills the child on Drop.
//!
//! ## Sanitized handle inheritance
//!
//! Both modes inherit ONLY the three stdio handles we resolve here. On
//! Windows we use `PROC_THREAD_ATTRIBUTE_HANDLE_LIST` to whitelist exactly
//! the resolved handles. On Unix the spawned child runs a `pre_exec` closure
//! that walks `/proc/self/fd` (or `/dev/fd`) and closes every fd > 2.
//!
//! Motivation: when a process tree has a pipe-redirected ancestor (Python
//! `subprocess.Popen(stdout=PIPE)`, IDE language-server hosts, CI runners,
//! etc.), every intermediate `CreateProcessW(bInheritHandles=TRUE)` on
//! Windows — and every `fork`+`exec` of a non-`O_CLOEXEC` fd on Unix —
//! duplicates that orphaned pipe write-end into the new child. The original
//! reader at the top never sees EOF.
//!
//! Issue: <https://github.com/zackees/running-process/issues/110>.

#[cfg(unix)]
use std::os::fd::BorrowedFd;
#[cfg(windows)]
use std::os::windows::io::BorrowedHandle;
use std::process::Command;
use std::time::Duration;

/// Selects the base environment used for a newly spawned process.
///
/// Explicit values added through [`Command::env`] or [`Command::envs`]
/// are applied after the selected base and therefore win on duplicate keys.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum EnvironmentPolicy {
    /// Choose from the process lifetime: contained subprocesses inherit,
    /// while detached daemons start from the logged-in user's baseline.
    #[default]
    Auto,
    /// Inherit the spawning process's environment.
    Inherit,
    /// Start from the logged-in user's machine + user environment.
    ///
    /// Windows implements this with `CreateEnvironmentBlock`. Unix
    /// reconstructs a clean login environment from the user's identity
    /// (`getpwuid_r` → `USER`/`LOGNAME`/`HOME`/`SHELL`, platform default
    /// `PATH`, carried-over locale/`TZ`/`TMPDIR`), falling back to
    /// inheritance only when the passwd entry cannot be resolved.
    UserBaseline,
    /// Start from an empty environment.
    Clear,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum SpawnLifetime {
    Contained,
    Daemon,
}

impl EnvironmentPolicy {
    pub(crate) fn resolve(self, lifetime: SpawnLifetime) -> Self {
        match (self, lifetime) {
            (Self::Auto, SpawnLifetime::Contained) => Self::Inherit,
            (Self::Auto, SpawnLifetime::Daemon) => Self::UserBaseline,
            (explicit, _) => explicit,
        }
    }
}

// ── Public API ──────────────────────────────────────────────────────────────

/// Caller-supplied stdio bindings for [`spawn`].
///
/// Each of `stdin`, `stdout`, `stderr` is independently a [`StdioSource`].
/// `drain_timeout` bounds the post-mortem wait the watcher thread applies
/// before force-closing any wrapper-held pipe ends so the parent observes
/// EOF after the child exits. `None` means the wrapper never auto-closes;
/// the parent is responsible for closing the pipes when it's done reading.
///
/// `show_console` (Windows-only effect) controls whether the child gets a
/// console window. Default is `false` — `CREATE_NO_WINDOW` is set, so the
/// child has no console regardless of how the parent was launched. Set this
/// to `true` only when you actually want the child to inherit / allocate a
/// console (interactive subprocess that should be visible to the user).
pub struct SpawnStdio<'a> {
    /// Source connected to the child's standard input.
    pub stdin: StdioSource<'a>,
    /// Source connected to the child's standard output.
    pub stdout: StdioSource<'a>,
    /// Source connected to the child's standard error.
    pub stderr: StdioSource<'a>,
    /// Maximum time the watcher waits before closing wrapper-held pipe ends.
    pub drain_timeout: Option<Duration>,
    /// Whether Windows children may inherit or allocate a visible console.
    pub show_console: bool,
}

impl Default for SpawnStdio<'_> {
    fn default() -> Self {
        Self {
            stdin: StdioSource::Null,
            stdout: StdioSource::Parent,
            stderr: StdioSource::Parent,
            drain_timeout: Some(Duration::from_secs(2)),
            show_console: false,
        }
    }
}

/// Per-slot source describing what the child should inherit for one of
/// stdin / stdout / stderr.
pub enum StdioSource<'a> {
    /// Connect this slot to the platform null device (`NUL` / `/dev/null`).
    Null,
    /// Inherit the parent's corresponding standard handle. The kernel
    /// receives a fresh inheritable duplicate; the parent's original slot
    /// is untouched.
    Parent,
    /// Bind this slot to a caller-owned OS handle. The wrapper duplicates
    /// the handle into an inheritable copy for the child; the caller
    /// retains its own handle and is responsible for closing it.
    #[cfg(windows)]
    Handle(BorrowedHandle<'a>),
    /// Bind this slot to a caller-owned file descriptor. Equivalent to
    /// `StdioSource::Handle` on Unix.
    #[cfg(unix)]
    Fd(BorrowedFd<'a>),
    /// Create a fresh anonymous pipe. The child gets one end; the parent
    /// gets the other via [`SpawnedChild`]'s `stdin` / `stdout` / `stderr`
    /// fields.
    Pipe,
    #[doc(hidden)]
    _Phantom(std::marker::PhantomData<&'a ()>),
}

// _Phantom is uninhabitable from outside: PhantomData<&'a ()> is a private
// constructor in practice (the variant is doc(hidden) and not constructed
// anywhere in this crate). It's only here so the `'a` lifetime is always
// used regardless of which cfg branch is active.

/// Handle to a detached daemon spawned via [`spawn_daemon`].
///
/// The daemon child always has stdin/stdout/stderr connected to the
/// platform null device (`NUL` on Windows, `/dev/null` on Unix) — a
/// detached process with inherited stdio is the classic crash-on-first-
/// `println!` failure mode after the parent closes its end, so the
/// daemon-spawn path forecloses that by construction. Dropping
/// `DaemonChild` does NOT terminate the daemon; it only closes the OS
/// handle the wrapper held. Call [`DaemonChild::kill`] to terminate.
pub struct DaemonChild {
    pid: u32,
    #[cfg(windows)]
    handle: imp::OwnedHandle,
    #[cfg(unix)]
    child: std::process::Child,
}

impl DaemonChild {
    /// Process ID.
    pub fn id(&self) -> u32 {
        self.pid
    }

    /// Forcibly terminate the child. Best-effort.
    pub fn kill(&mut self) -> std::io::Result<()> {
        #[cfg(windows)]
        {
            imp::terminate(&self.handle)
        }
        #[cfg(unix)]
        {
            self.child.kill()
        }
    }

    /// Block until the child exits and return its exit code.
    pub fn wait(&mut self) -> std::io::Result<i32> {
        #[cfg(windows)]
        {
            imp::wait(&self.handle)
        }
        #[cfg(unix)]
        {
            let status = self.child.wait()?;
            Ok(unix_exit_code(status))
        }
    }

    /// Non-blocking variant of [`Self::wait`].
    pub fn try_wait(&mut self) -> std::io::Result<Option<i32>> {
        #[cfg(windows)]
        {
            imp::try_wait(&self.handle)
        }
        #[cfg(unix)]
        {
            Ok(self.child.try_wait()?.map(unix_exit_code))
        }
    }
}

/// Handle to a contained child spawned via [`spawn`].
///
/// On Drop, `SpawnedChild` synchronously kills the child:
///   * Windows: closes the Job Object handle; `KILL_ON_JOB_CLOSE` causes the
///     kernel to terminate every process in the job (the child and its
///     descendants).
///   * Unix: `killpg(pgid, SIGKILL)` and `waitpid` to reap.
///
/// The optional `stdin` / `stdout` / `stderr` fields are present when the
/// corresponding [`StdioSource`] was [`StdioSource::Pipe`]; otherwise they
/// are `None`.
pub struct SpawnedChild {
    /// Parent-side pipe for writing to child stdin when requested.
    pub stdin: Option<std::process::ChildStdin>,
    /// Parent-side pipe for reading child stdout when requested.
    pub stdout: Option<std::process::ChildStdout>,
    /// Parent-side pipe for reading child stderr when requested.
    pub stderr: Option<std::process::ChildStderr>,
    pid: u32,
    #[cfg(windows)]
    inner: imp::SpawnedInner,
    #[cfg(unix)]
    inner: unix_impl::SpawnedInner,
}

impl SpawnedChild {
    /// Process ID of the spawned child.
    pub fn id(&self) -> u32 {
        self.pid
    }

    /// Forcibly terminate the child. Best-effort.
    pub fn kill(&mut self) -> std::io::Result<()> {
        #[cfg(windows)]
        {
            self.inner.kill()
        }
        #[cfg(unix)]
        {
            self.inner.kill()
        }
    }

    /// Block until the child exits and return its exit code.
    pub fn wait(&mut self) -> std::io::Result<i32> {
        #[cfg(windows)]
        {
            self.inner.wait()
        }
        #[cfg(unix)]
        {
            self.inner.wait()
        }
    }

    /// Non-blocking variant of [`Self::wait`].
    pub fn try_wait(&mut self) -> std::io::Result<Option<i32>> {
        #[cfg(windows)]
        {
            self.inner.try_wait()
        }
        #[cfg(unix)]
        {
            self.inner.try_wait()
        }
    }
}

impl Drop for SpawnedChild {
    fn drop(&mut self) {
        #[cfg(windows)]
        {
            self.inner.shutdown();
        }
        #[cfg(unix)]
        {
            self.inner.shutdown();
        }
    }
}

/// Spawn `command` as a detached daemon. NUL stdio, sanitized handles,
/// no console window, ignores parent's Ctrl-C / SIGINT (Windows:
/// `CREATE_NEW_PROCESS_GROUP` + `DETACHED_PROCESS`; Unix: `setsid` puts the
/// daemon in a new session so it's not in the parent's foreground group).
///
/// The NUL-stdio guarantee is enforced internally by the platform impls
/// and is not configurable — a detached daemon needs sunk stdio to
/// avoid crashing on later `println!`/`eprintln!` after the parent
/// closes its handles.
pub fn spawn_daemon(command: &mut Command) -> std::io::Result<DaemonChild> {
    spawn_daemon_with_env_policy(command, EnvironmentPolicy::Auto)
}

/// Like [`spawn_daemon`] but with explicit control over whether the
/// daemon's inherited env is passed through to the child.
///
/// `clear_env = false` uses [`EnvironmentPolicy::Auto`], matching
/// [`spawn_daemon`].
///
/// `clear_env = true`: child sees ONLY the explicit `command.env(...)`
/// entries. Mirrors `command.env_clear()` semantics for callers using
/// the manual `CreateProcessW` path (Rust stdlib's `env_clear` flag
/// isn't observable through `Command::get_envs`, so our sanitized
/// spawn machinery can't otherwise honour it).
pub fn spawn_daemon_with_clear_env(
    command: &mut Command,
    clear_env: bool,
) -> std::io::Result<DaemonChild> {
    let policy = if clear_env {
        EnvironmentPolicy::Clear
    } else {
        EnvironmentPolicy::Auto
    };
    spawn_daemon_with_env_policy(command, policy)
}

/// Spawn a detached daemon using an explicit environment policy.
pub fn spawn_daemon_with_env_policy(
    command: &mut Command,
    policy: EnvironmentPolicy,
) -> std::io::Result<DaemonChild> {
    let policy = policy.resolve(SpawnLifetime::Daemon);
    #[cfg(windows)]
    {
        imp::spawn_daemon(command, policy)
    }
    #[cfg(unix)]
    {
        unix_impl::spawn_daemon(command, policy)
    }
}

/// Spawn `command` as a contained child with caller-controlled stdio.
/// Sanitized handles, CREATE_NO_WINDOW. Child dies when the returned
/// [`SpawnedChild`] is dropped.
pub fn spawn(command: &mut Command, stdio: SpawnStdio<'_>) -> std::io::Result<SpawnedChild> {
    spawn_with_env_policy(command, stdio, EnvironmentPolicy::Auto)
}

/// Spawn a contained child using an explicit environment policy.
pub fn spawn_with_env_policy(
    command: &mut Command,
    stdio: SpawnStdio<'_>,
    policy: EnvironmentPolicy,
) -> std::io::Result<SpawnedChild> {
    let policy = policy.resolve(SpawnLifetime::Contained);
    #[cfg(windows)]
    {
        imp::spawn(command, stdio, policy)
    }
    #[cfg(unix)]
    {
        unix_impl::spawn(command, stdio, policy)
    }
}

#[cfg(unix)]
fn unix_exit_code(status: std::process::ExitStatus) -> i32 {
    use std::os::unix::process::ExitStatusExt;
    status
        .code()
        .unwrap_or_else(|| -status.signal().unwrap_or(1))
}

// ── Windows implementation ──────────────────────────────────────────────────

#[cfg(windows)]
#[path = "spawn_imp_windows.rs"]
mod imp;

#[cfg(unix)]
#[path = "spawn_imp_unix.rs"]
mod unix_impl;
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn spawn_stdio_default_has_sane_values() {
        let s = SpawnStdio::default();
        assert!(matches!(s.stdin, StdioSource::Null));
        assert!(matches!(s.stdout, StdioSource::Parent));
        assert!(matches!(s.stderr, StdioSource::Parent));
        assert_eq!(s.drain_timeout, Some(Duration::from_secs(2)));
        // No console window by default — opt-in only.
        assert!(!s.show_console);
    }

    #[test]
    fn auto_environment_policy_depends_on_lifetime() {
        assert_eq!(
            EnvironmentPolicy::Auto.resolve(SpawnLifetime::Contained),
            EnvironmentPolicy::Inherit
        );
        assert_eq!(
            EnvironmentPolicy::Auto.resolve(SpawnLifetime::Daemon),
            EnvironmentPolicy::UserBaseline
        );
    }

    #[test]
    fn explicit_environment_policy_is_not_rewritten() {
        for policy in [
            EnvironmentPolicy::Inherit,
            EnvironmentPolicy::UserBaseline,
            EnvironmentPolicy::Clear,
        ] {
            assert_eq!(policy.resolve(SpawnLifetime::Contained), policy);
            assert_eq!(policy.resolve(SpawnLifetime::Daemon), policy);
        }
    }
}