std/os/unix/process.rs
1//! Unix-specific extensions to primitives in the [`std::process`] module.
2//!
3//! [`std::process`]: crate::process
4
5#![stable(feature = "rust1", since = "1.0.0")]
6
7use crate::ffi::OsStr;
8use crate::macros::rustdoc_skip_body;
9use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd};
10use crate::path::Path;
11#[cfg(doc)]
12use crate::process::{ExitStatus, ExitStatusError};
13use crate::sys::process::ChildPipe;
14use crate::sys::{AsInner, AsInnerMut, FromInner, IntoInner};
15use crate::{io, process, sys};
16
17cfg_select! {
18 any(target_os = "vxworks", target_os = "espidf", target_os = "horizon", target_os = "vita") => {
19 type UserId = u16;
20 type GroupId = u16;
21 }
22 any(target_os = "nto", target_os = "qnx") => {
23 // Both IDs are signed, see `sys/target_nto.h` of the QNX SDP.
24 // Only positive values should be used, see e.g.
25 // https://www.qnx.com/developers/docs/7.1/com.qnx.doc.neutrino.lib_ref/topic/s/setuid.html
26 type UserId = i32;
27 type GroupId = i32;
28 }
29 _ => {
30 type UserId = u32;
31 type GroupId = u32;
32 }
33}
34
35/// Unix-specific extensions to the [`process::Command`] builder.
36#[stable(feature = "rust1", since = "1.0.0")]
37pub impl(self) trait CommandExt {
38 /// Sets the child process's user ID. This translates to a
39 /// `setuid` call in the child process. Failure in the `setuid`
40 /// call will cause the spawn to fail.
41 ///
42 /// # Notes
43 ///
44 /// This will also trigger a call to `setgroups(0, NULL)` in the child
45 /// process if no groups have been specified.
46 /// This removes supplementary groups that might have given the child
47 /// unwanted permissions.
48 #[stable(feature = "rust1", since = "1.0.0")]
49 fn uid(&mut self, id: UserId) -> &mut process::Command;
50
51 /// Similar to `uid`, but sets the group ID of the child process. This has
52 /// the same semantics as the `uid` field.
53 #[stable(feature = "rust1", since = "1.0.0")]
54 fn gid(&mut self, id: GroupId) -> &mut process::Command;
55
56 /// Sets the supplementary group IDs for the calling process. Translates to
57 /// a `setgroups` call in the child process.
58 #[unstable(feature = "setgroups", issue = "90747")]
59 fn groups(&mut self, groups: &[GroupId]) -> &mut process::Command;
60
61 /// Schedules a closure to be run just before the `exec` function is
62 /// invoked.
63 ///
64 /// The closure is allowed to return an I/O error whose OS error code will
65 /// be communicated back to the parent and returned as an error from when
66 /// the spawn was requested.
67 ///
68 /// Multiple closures can be registered and they will be called in order of
69 /// their registration. If a closure returns `Err` then no further closures
70 /// will be called and the spawn operation will immediately return with a
71 /// failure.
72 ///
73 /// # Notes and Safety
74 ///
75 /// This closure will be run in the context of the child process after a
76 /// `fork`. This primarily means that any modifications made to memory on
77 /// behalf of this closure will **not** be visible to the parent process.
78 /// This is often a very constrained environment where normal operations
79 /// like `malloc`, accessing environment variables through [`std::env`]
80 /// or acquiring a mutex are not guaranteed to work (due to
81 /// other threads perhaps still running when the `fork` was run).
82 ///
83 /// Note that the list of allocating functions includes [`Error::new`] and
84 /// [`Error::other`]. To signal a non-trivial error, prefer [`panic!`].
85 ///
86 /// For further details refer to the [POSIX fork() specification]
87 /// and the equivalent documentation for any targeted
88 /// platform, especially the requirements around *async-signal-safety*.
89 ///
90 /// This also means that all resources such as file descriptors and
91 /// memory-mapped regions got duplicated. It is your responsibility to make
92 /// sure that the closure does not violate library invariants by making
93 /// invalid use of these duplicates.
94 ///
95 /// Panicking in the closure is safe only if all the format arguments for the
96 /// panic message can be safely formatted; this is because although
97 /// `Command` calls [`std::panic::always_abort`](crate::panic::always_abort)
98 /// before calling the pre_exec hook, panic will still try to format the
99 /// panic message.
100 ///
101 /// When this closure is run, aspects such as the stdio file descriptors and
102 /// working directory have successfully been changed, so output to these
103 /// locations might not appear where intended.
104 ///
105 /// [POSIX fork() specification]:
106 /// https://pubs.opengroup.org/onlinepubs/9799919799/functions/fork.html
107 /// [`std::env`]: mod@crate::env
108 /// [`Error::new`]: ../../../io/struct.Error.html#method.new
109 /// [`Error::other`]: ../../../io/struct.Error.html#method.other
110 #[stable(feature = "process_pre_exec", since = "1.34.0")]
111 unsafe fn pre_exec<F>(&mut self, f: F) -> &mut process::Command
112 where
113 F: FnMut() -> io::Result<()> + Send + Sync + 'static;
114
115 /// Schedules a closure to be run just before the `exec` function is
116 /// invoked.
117 ///
118 /// `before_exec` used to be a safe method, but it needs to be unsafe since the closure may only
119 /// perform operations that are *async-signal-safe*. Hence it got deprecated in favor of the
120 /// unsafe [`pre_exec`]. Meanwhile, Rust gained the ability to make an existing safe method
121 /// fully unsafe in a new edition, which is how `before_exec` became `unsafe`. It still also
122 /// remains deprecated; `pre_exec` should be used instead.
123 ///
124 /// [`pre_exec`]: CommandExt::pre_exec
125 #[stable(feature = "process_exec", since = "1.15.0")]
126 #[deprecated(since = "1.37.0", note = "should be unsafe, use `pre_exec` instead")]
127 #[rustc_deprecated_safe_2024(audit_that = "the closure is async-signal-safe")]
128 unsafe fn before_exec<F>(&mut self, f: F) -> &mut process::Command
129 where
130 F: FnMut() -> io::Result<()> + Send + Sync + 'static,
131 {
132 unsafe { self.pre_exec(f) }
133 }
134
135 /// Performs all the required setup by this `Command`, followed by calling
136 /// the `execvp` syscall.
137 ///
138 /// On success this function will not return, and otherwise it will return
139 /// an error indicating why the exec (or another part of the setup of the
140 /// `Command`) failed.
141 ///
142 /// `exec` not returning has the same implications as calling
143 /// [`process::exit`] – no destructors on the current stack or any other
144 /// thread’s stack will be run. Therefore, it is recommended to only call
145 /// `exec` at a point where it is fine to not run any destructors. Note,
146 /// that the `execvp` syscall independently guarantees that all memory is
147 /// freed and all file descriptors with the `CLOEXEC` option (set by default
148 /// on all file descriptors opened by the standard library) are closed.
149 ///
150 /// This function, unlike `spawn`, will **not** `fork` the process to create
151 /// a new child. Like spawn, however, the default behavior for the stdio
152 /// descriptors will be to inherit them from the current process.
153 ///
154 /// # Notes
155 ///
156 /// The process may be in a "broken state" if this function returns in
157 /// error. For example the working directory, environment variables, signal
158 /// handling settings, various user/group information, or aspects of stdio
159 /// file descriptors may have changed. If a "transactional spawn" is
160 /// required to gracefully handle errors it is recommended to use the
161 /// cross-platform `spawn` instead.
162 #[stable(feature = "process_exec2", since = "1.9.0")]
163 #[must_use]
164 fn exec(&mut self) -> io::Error;
165
166 /// Set executable argument
167 ///
168 /// Set the first process argument, `argv[0]`, to something other than the
169 /// default executable path.
170 #[stable(feature = "process_set_argv0", since = "1.45.0")]
171 fn arg0<S>(&mut self, arg: S) -> &mut process::Command
172 where
173 S: AsRef<OsStr>;
174
175 /// Sets the process group ID (PGID) of the child process. Equivalent to a
176 /// `setpgid` call in the child process, but may be more efficient.
177 ///
178 /// Process groups determine which processes receive signals.
179 ///
180 /// # Examples
181 ///
182 /// Pressing Ctrl-C in a terminal will send SIGINT to all processes in
183 /// the current foreground process group. By spawning the `sleep`
184 /// subprocess in a new process group, it will not receive SIGINT from the
185 /// terminal.
186 ///
187 /// The parent process could install a signal handler and manage the
188 /// subprocess on its own terms.
189 ///
190 /// A process group ID of 0 will use the process ID as the PGID.
191 ///
192 #[cfg_attr(target_family = "unix", doc = "```no_run")]
193 #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
194 /// use std::process::Command;
195 /// use std::os::unix::process::CommandExt;
196 ///
197 /// Command::new("sleep")
198 /// .arg("10")
199 /// .process_group(0)
200 /// .spawn()?
201 /// .wait()?;
202 /// #
203 /// # Ok::<_, Box<dyn std::error::Error>>(())
204 /// ```
205 #[stable(feature = "process_set_process_group", since = "1.64.0")]
206 fn process_group(&mut self, pgroup: i32) -> &mut process::Command;
207
208 /// Set the root of the child process. This calls `chroot` in the child process before executing
209 /// the command.
210 ///
211 /// This happens before changing to the directory specified with
212 /// [`process::Command::current_dir`], and that directory will be relative to the new root.
213 ///
214 /// If no directory has been specified with [`process::Command::current_dir`], this will set the
215 /// directory to `/`, to avoid leaving the current directory outside the chroot. (This is an
216 /// intentional difference from the underlying `chroot` system call.)
217 ///
218 /// This typically requires privileges, such as root or a specific capability.
219 ///
220 /// Note that `chroot` is not guaranteed to be async-signal-safe on all OSes, and functions
221 /// called between `fork` and `exec` must be async-signal-safe. However, in practice, the
222 /// ability to `fork` then `chroot` then `exec` is a capability widely provided by Rust targets
223 /// and relied upon by numerous programs.
224 ///
225 /// `chroot` is not, by itself, a complete security or sandboxing measure. It may form some part
226 /// of a containment mechanism, but fully containing a process requires additional steps.
227 ///
228 /// See the [`chroot`] manual page for more details.
229 ///
230 /// [`chroot`]: https://man7.org/linux/man-pages/man2/chroot.2.html
231 ///
232 /// # Examples
233 ///
234 #[cfg_attr(target_family = "unix", doc = "```no_run")]
235 #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
236 /// #![feature(process_chroot)]
237 /// use std::process::Command;
238 /// use std::os::unix::process::CommandExt;
239 ///
240 /// Command::new("binary-within-new-root")
241 /// .chroot("/new-root")
242 /// .spawn()?
243 /// .wait()?;
244 /// #
245 /// # Ok::<_, Box<dyn std::error::Error>>(())
246 #[doc = "```"]
247 #[unstable(feature = "process_chroot", issue = "141298")]
248 fn chroot<P: AsRef<Path>>(&mut self, dir: P) -> &mut process::Command;
249
250 #[unstable(feature = "process_setsid", issue = "105376")]
251 fn setsid(&mut self, setsid: bool) -> &mut process::Command;
252}
253
254#[stable(feature = "rust1", since = "1.0.0")]
255impl CommandExt for process::Command {
256 #[rustdoc_skip_body]
257 fn uid(&mut self, id: UserId) -> &mut process::Command {
258 self.as_inner_mut().uid(id);
259 self
260 }
261
262 #[rustdoc_skip_body]
263 fn gid(&mut self, id: GroupId) -> &mut process::Command {
264 self.as_inner_mut().gid(id);
265 self
266 }
267
268 #[rustdoc_skip_body]
269 fn groups(&mut self, groups: &[GroupId]) -> &mut process::Command {
270 self.as_inner_mut().groups(groups);
271 self
272 }
273
274 #[rustdoc_skip_body]
275 unsafe fn pre_exec<F>(&mut self, f: F) -> &mut process::Command
276 where
277 F: FnMut() -> io::Result<()> + Send + Sync + 'static,
278 {
279 self.as_inner_mut().pre_exec(Box::new(f));
280 self
281 }
282
283 #[rustdoc_skip_body]
284 fn exec(&mut self) -> io::Error {
285 // NOTE: This may *not* be safe to call after `libc::fork`, because it
286 // may allocate. That may be worth fixing at some point in the future.
287 self.as_inner_mut().exec(sys::process::Stdio::Inherit)
288 }
289
290 #[rustdoc_skip_body]
291 fn arg0<S>(&mut self, arg: S) -> &mut process::Command
292 where
293 S: AsRef<OsStr>,
294 {
295 self.as_inner_mut().set_arg_0(arg.as_ref());
296 self
297 }
298
299 #[rustdoc_skip_body]
300 fn process_group(&mut self, pgroup: i32) -> &mut process::Command {
301 self.as_inner_mut().pgroup(pgroup);
302 self
303 }
304
305 #[rustdoc_skip_body]
306 fn chroot<P: AsRef<Path>>(&mut self, dir: P) -> &mut process::Command {
307 self.as_inner_mut().chroot(dir.as_ref());
308 self
309 }
310
311 #[rustdoc_skip_body]
312 fn setsid(&mut self, setsid: bool) -> &mut process::Command {
313 self.as_inner_mut().setsid(setsid);
314 self
315 }
316}
317
318/// Unix-specific extensions to [`ExitStatus`] and [`ExitStatusError`].
319///
320/// On Unix, [`ExitStatus`] **does not necessarily represent an exit status**, as
321/// passed to the `_exit` system call or returned by
322/// [`ExitStatus::code()`](ExitStatus::code). It represents **any wait status**
323/// as returned by one of the [`wait`] family of system
324/// calls.
325///
326/// A Unix wait status (a Rust [`ExitStatus`]) can represent a Unix exit status, but can also
327/// represent other kinds of process event.
328///
329/// [`wait`]: https://pubs.opengroup.org/onlinepubs/9799919799/functions/wait.html
330#[stable(feature = "rust1", since = "1.0.0")]
331pub impl(self) trait ExitStatusExt {
332 /// Creates a new [`ExitStatus`] or [`ExitStatusError`] from the raw underlying integer status
333 /// value from [`wait`].
334 ///
335 /// The value should be a **wait status, not an exit status**.
336 ///
337 /// # Example
338 ///
339 /// A signal-terminated [`wait`] status carries the signal number, which [`ExitStatus::signal`]
340 /// recovers using the platform's [`WTERMSIG`][`wait`] macro. Note that the bit layout of a
341 /// wait status is **not** specified by POSIX and is platform-specific. By convention on most
342 /// Unix platforms, the signal number occupies the low 7 bits with the exit-code byte left
343 /// zero, so a bare signal number between 1 and 126 is treated as a signal-terminated wait
344 /// status. The following example relies on that convention and is therefore not guaranteed to
345 /// hold on every target:
346 ///
347 #[cfg_attr(target_family = "unix", doc = "```no_run")]
348 #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
349 /// # if cfg!(target_os = "fuchsia") { return; }
350 /// use std::os::unix::process::ExitStatusExt;
351 /// use std::process::ExitStatus;
352 ///
353 /// let signal = 15; // SIGTERM
354 /// assert!(signal > 0 && signal < 0x7f, "not a valid Unix termination signal: {signal}");
355 ///
356 /// let status = ExitStatus::from_raw(signal);
357 /// assert!(!status.success());
358 /// assert_eq!(status.code(), None);
359 /// assert_eq!(status.signal(), Some(15));
360 /// ```
361 ///
362 /// Generating an [`ExitStatus`] with a given exit code (0-255) is system-dependent.
363 /// The value returned by [`ExitStatus::code`] is specified to come from applying the
364 /// [`WEXITSTATUS`][`wait`] macro, but there is no POSIX-specified constructor and the bit
365 /// layout is left unspecified. By near-universal convention every Unix libc stores the
366 /// 8-bit exit code in bits 8..16, so a status built with `(code & 0xff) << 8` will usually
367 /// round-trip back to the original exit code:
368 ///
369 #[cfg_attr(target_family = "unix", doc = "```no_run")]
370 #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
371 /// # if cfg!(target_os = "fuchsia") { return; }
372 /// use std::os::unix::process::ExitStatusExt;
373 /// use std::process::ExitStatus;
374 ///
375 /// let code = 41;
376 /// let status = ExitStatus::from_raw((code & 0xff) << 8);
377 /// assert_eq!(status.code(), Some(41));
378 /// assert!(!status.success());
379 /// ```
380 ///
381 /// # Panics
382 ///
383 /// - `ExitStatusError::from_raw` panics on an attempt to make an [`ExitStatusError`] from a
384 /// [`wait`] status of `0`.
385 /// - `ExitStatus::from_raw` always succeeds and never panics.
386 ///
387 /// [`wait`]: https://pubs.opengroup.org/onlinepubs/9799919799/functions/wait.html
388 #[stable(feature = "exit_status_from", since = "1.12.0")]
389 fn from_raw(raw: i32) -> Self;
390
391 /// If the process was terminated by a signal, returns that signal.
392 ///
393 /// In other words, if [`WIFSIGNALED`][`wait`], this returns [`WTERMSIG`][`wait`]. For such a status,
394 /// [`ExitStatus::code`] returns `None`:
395 ///
396 #[cfg_attr(target_family = "unix", doc = "```no_run")]
397 #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
398 /// # if cfg!(target_os = "fuchsia") { return; }
399 /// use std::os::unix::process::ExitStatusExt;
400 /// use std::process::ExitStatus;
401 ///
402 /// let sigterm = 15;
403 /// let status = ExitStatus::from_raw(sigterm);
404 /// assert_eq!(status.code(), None);
405 /// assert_eq!(status.signal(), Some(sigterm));
406 /// ```
407 ///
408 /// A process that receives a signal may catch and handle it, then exit normally with an
409 /// exit code. When that happens, `signal` returns `None`.
410 ///
411 /// Rust does not pass commands through a shell, such as `bash` and `sh`, but it
412 /// is possible to do so manually. When invoking a shell, the signal value indicates whether
413 /// the top-level shell itself received a terminating signal. If instead a command *within*
414 /// an invoked shell receives a terminating signal, many shells convert the signal number
415 /// into an exit code by adding 128. For example, a command run under `sh` that receives a
416 /// [`SIGTERM`] canonically causes the shell to report an exit code of `15 + 128`, i.e. `143`.
417 ///
418 /// [`SIGTERM`]: https://pubs.opengroup.org/onlinepubs/9799919799/utilities/kill.html
419 /// [`wait`]: https://pubs.opengroup.org/onlinepubs/9799919799/functions/wait.html
420 #[stable(feature = "rust1", since = "1.0.0")]
421 fn signal(&self) -> Option<i32>;
422
423 /// If the process was terminated by a signal, says whether it dumped core.
424 #[stable(feature = "unix_process_wait_more", since = "1.58.0")]
425 fn core_dumped(&self) -> bool;
426
427 /// If the process was stopped by a signal, returns that signal.
428 ///
429 /// In other words, if [`WIFSTOPPED`][`wait`], this returns [`WSTOPSIG`][`wait`]. This is only possible if the status came from
430 /// a [`wait`] system call which was passed [`WUNTRACED`][`wait`], and was then converted into an [`ExitStatus`].
431 ///
432 /// [`wait`]: https://pubs.opengroup.org/onlinepubs/9799919799/functions/wait.html
433 #[stable(feature = "unix_process_wait_more", since = "1.58.0")]
434 fn stopped_signal(&self) -> Option<i32>;
435
436 /// Whether the process was continued from a stopped status.
437 ///
438 /// I.e. [`WIFCONTINUED`][`wait`]. This is only possible if the status came from a [`wait`] system call
439 /// which was passed [`WCONTINUED`][`wait`], and was then converted into an [`ExitStatus`].
440 ///
441 /// [`wait`]: https://pubs.opengroup.org/onlinepubs/9799919799/functions/wait.html
442 #[stable(feature = "unix_process_wait_more", since = "1.58.0")]
443 fn continued(&self) -> bool;
444
445 /// Returns the underlying raw [`wait`] status.
446 ///
447 /// The returned integer is a **wait status, not an exit status**.
448 ///
449 /// [`wait`]: https://pubs.opengroup.org/onlinepubs/9799919799/functions/wait.html
450 #[stable(feature = "unix_process_wait_more", since = "1.58.0")]
451 fn into_raw(self) -> i32;
452}
453
454#[stable(feature = "rust1", since = "1.0.0")]
455impl ExitStatusExt for process::ExitStatus {
456 #[rustdoc_skip_body]
457 fn from_raw(raw: i32) -> Self {
458 process::ExitStatus::from_inner(From::from(raw))
459 }
460
461 #[rustdoc_skip_body]
462 fn signal(&self) -> Option<i32> {
463 self.as_inner().signal()
464 }
465
466 #[rustdoc_skip_body]
467 fn core_dumped(&self) -> bool {
468 self.as_inner().core_dumped()
469 }
470
471 #[rustdoc_skip_body]
472 fn stopped_signal(&self) -> Option<i32> {
473 self.as_inner().stopped_signal()
474 }
475
476 #[rustdoc_skip_body]
477 fn continued(&self) -> bool {
478 self.as_inner().continued()
479 }
480
481 #[rustdoc_skip_body]
482 fn into_raw(self) -> i32 {
483 self.as_inner().into_raw().into()
484 }
485}
486
487#[unstable(feature = "exit_status_error", issue = "84908")]
488impl ExitStatusExt for process::ExitStatusError {
489 fn from_raw(raw: i32) -> Self {
490 process::ExitStatus::from_raw(raw)
491 .exit_ok()
492 .expect_err("<ExitStatusError as ExitStatusExt>::from_raw(0) but zero is not an error")
493 }
494
495 fn signal(&self) -> Option<i32> {
496 self.into_status().signal()
497 }
498
499 fn core_dumped(&self) -> bool {
500 self.into_status().core_dumped()
501 }
502
503 fn stopped_signal(&self) -> Option<i32> {
504 self.into_status().stopped_signal()
505 }
506
507 fn continued(&self) -> bool {
508 self.into_status().continued()
509 }
510
511 fn into_raw(self) -> i32 {
512 self.into_status().into_raw()
513 }
514}
515
516#[unstable(feature = "unix_send_signal", issue = "141975")]
517pub impl(self) trait ChildExt {
518 /// Sends a signal to a child process.
519 ///
520 /// # Errors
521 ///
522 /// This function will return an error if the signal is invalid. The integer values associated
523 /// with signals are implementation-specific, so it's encouraged to use a crate that provides
524 /// posix bindings.
525 ///
526 /// # Examples
527 ///
528 #[cfg_attr(target_family = "unix", doc = "```no_run")]
529 #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
530 /// #![feature(unix_send_signal)]
531 ///
532 /// use std::{io, os::unix::process::ChildExt, process::{Command, Stdio}};
533 ///
534 /// use libc::SIGTERM;
535 ///
536 /// fn main() -> io::Result<()> {
537 /// # if cfg!(not(all(target_vendor = "apple", not(target_os = "macos")))) {
538 /// let child = Command::new("cat").stdin(Stdio::piped()).spawn()?;
539 /// child.send_signal(SIGTERM)?;
540 /// # }
541 /// Ok(())
542 /// }
543 /// ```
544 fn send_signal(&self, signal: i32) -> io::Result<()>;
545
546 /// Sends a signal to a child process's process group.
547 ///
548 /// # Errors
549 ///
550 /// This function will return an error if the signal is invalid or if the
551 /// child process does not have a process group. The integer values
552 /// associated with signals are implementation-specific, so it's encouraged
553 /// to use a crate that provides posix bindings.
554 ///
555 /// # Examples
556 ///
557 #[cfg_attr(target_family = "unix", doc = "```no_run")]
558 #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
559 /// #![feature(unix_send_signal)]
560 ///
561 /// use std::{io, os::unix::process::{ChildExt, CommandExt}, process::{Command, Stdio}};
562 ///
563 /// use libc::SIGTERM;
564 ///
565 /// fn main() -> io::Result<()> {
566 /// # if cfg!(not(all(target_vendor = "apple", not(target_os = "macos")))) {
567 /// let child = Command::new("cat")
568 /// .stdin(Stdio::piped())
569 /// .process_group(0)
570 /// .spawn()?;
571 /// child.send_process_group_signal(SIGTERM)?;
572 /// # }
573 /// Ok(())
574 /// }
575 /// ```
576 #[unstable(feature = "unix_send_signal", issue = "141975")]
577 fn send_process_group_signal(&self, signal: i32) -> io::Result<()>;
578
579 /// Forces the child process's process group to exit.
580 ///
581 /// This is analogous to [`Child::kill`] but applies to every process in
582 /// the child process's process group.
583 ///
584 /// Use [`CommandExt::process_group`] to assign a child process to an
585 /// existing process group, or to make it the leader of a new process group.
586 /// By default spawned processes are in the parent's process group.
587 ///
588 /// # Examples
589 ///
590 #[cfg_attr(target_family = "unix", doc = "```no_run")]
591 #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
592 /// #![feature(unix_kill_process_group)]
593 ///
594 /// use std::{os::unix::process::{ChildExt, CommandExt}, process::{Command, Stdio}};
595 ///
596 /// fn main() -> std::io::Result<()> {
597 /// let mut child = Command::new("cat")
598 /// .stdin(Stdio::piped())
599 /// .process_group(0)
600 /// .spawn()?;
601 /// child.kill_process_group()?;
602 /// Ok(())
603 /// }
604 /// ```
605 ///
606 /// [`Child::kill`]: process::Child::kill
607 #[unstable(feature = "unix_kill_process_group", issue = "156537")]
608 fn kill_process_group(&mut self) -> io::Result<()>;
609}
610
611#[unstable(feature = "unix_send_signal", issue = "141975")]
612impl ChildExt for process::Child {
613 #[rustdoc_skip_body]
614 fn send_signal(&self, signal: i32) -> io::Result<()> {
615 self.handle.send_signal(signal)
616 }
617
618 #[rustdoc_skip_body]
619 fn send_process_group_signal(&self, signal: i32) -> io::Result<()> {
620 self.handle.send_process_group_signal(signal)
621 }
622
623 #[cfg(not(target_os = "espidf"))]
624 #[rustdoc_skip_body]
625 fn kill_process_group(&mut self) -> io::Result<()> {
626 self.handle.send_process_group_signal(libc::SIGKILL)
627 }
628
629 #[cfg(target_os = "espidf")]
630 fn kill_process_group(&mut self) -> io::Result<()> {
631 Err(io::Error::new(
632 io::ErrorKind::Unsupported,
633 "process groups are not supported on espidf",
634 ))
635 }
636}
637
638#[stable(feature = "process_extensions", since = "1.2.0")]
639impl FromRawFd for process::Stdio {
640 #[inline]
641 #[rustdoc_skip_body]
642 unsafe fn from_raw_fd(fd: RawFd) -> process::Stdio {
643 let fd = sys::fd::FileDesc::from_raw_fd(fd);
644 let io = sys::process::Stdio::Fd(fd);
645 process::Stdio::from_inner(io)
646 }
647}
648
649#[stable(feature = "io_safety", since = "1.63.0")]
650impl From<OwnedFd> for process::Stdio {
651 /// Takes ownership of a file descriptor and returns a [`Stdio`](process::Stdio)
652 /// that can attach a stream to it.
653 #[inline]
654 #[rustdoc_skip_body]
655 fn from(fd: OwnedFd) -> process::Stdio {
656 let fd = sys::fd::FileDesc::from_inner(fd);
657 let io = sys::process::Stdio::Fd(fd);
658 process::Stdio::from_inner(io)
659 }
660}
661
662#[stable(feature = "process_extensions", since = "1.2.0")]
663impl AsRawFd for process::ChildStdin {
664 #[inline]
665 #[rustdoc_skip_body]
666 fn as_raw_fd(&self) -> RawFd {
667 self.as_inner().as_raw_fd()
668 }
669}
670
671#[stable(feature = "process_extensions", since = "1.2.0")]
672impl AsRawFd for process::ChildStdout {
673 #[inline]
674 #[rustdoc_skip_body]
675 fn as_raw_fd(&self) -> RawFd {
676 self.as_inner().as_raw_fd()
677 }
678}
679
680#[stable(feature = "process_extensions", since = "1.2.0")]
681impl AsRawFd for process::ChildStderr {
682 #[inline]
683 #[rustdoc_skip_body]
684 fn as_raw_fd(&self) -> RawFd {
685 self.as_inner().as_raw_fd()
686 }
687}
688
689#[stable(feature = "into_raw_os", since = "1.4.0")]
690impl IntoRawFd for process::ChildStdin {
691 #[inline]
692 #[rustdoc_skip_body]
693 fn into_raw_fd(self) -> RawFd {
694 self.into_inner().into_inner().into_raw_fd()
695 }
696}
697
698#[stable(feature = "into_raw_os", since = "1.4.0")]
699impl IntoRawFd for process::ChildStdout {
700 #[inline]
701 #[rustdoc_skip_body]
702 fn into_raw_fd(self) -> RawFd {
703 self.into_inner().into_inner().into_raw_fd()
704 }
705}
706
707#[stable(feature = "into_raw_os", since = "1.4.0")]
708impl IntoRawFd for process::ChildStderr {
709 #[inline]
710 #[rustdoc_skip_body]
711 fn into_raw_fd(self) -> RawFd {
712 self.into_inner().into_inner().into_raw_fd()
713 }
714}
715
716#[stable(feature = "io_safety", since = "1.63.0")]
717impl AsFd for crate::process::ChildStdin {
718 #[inline]
719 #[rustdoc_skip_body]
720 fn as_fd(&self) -> BorrowedFd<'_> {
721 self.as_inner().as_fd()
722 }
723}
724
725#[stable(feature = "io_safety", since = "1.63.0")]
726impl From<crate::process::ChildStdin> for OwnedFd {
727 /// Takes ownership of a [`ChildStdin`](crate::process::ChildStdin)'s file descriptor.
728 #[inline]
729 #[rustdoc_skip_body]
730 fn from(child_stdin: crate::process::ChildStdin) -> OwnedFd {
731 child_stdin.into_inner().into_inner()
732 }
733}
734
735/// Creates a `ChildStdin` from the provided `OwnedFd`.
736///
737/// The provided file descriptor must point to a pipe
738/// with the `CLOEXEC` flag set.
739#[stable(feature = "child_stream_from_fd", since = "1.74.0")]
740impl From<OwnedFd> for process::ChildStdin {
741 #[inline]
742 #[rustdoc_skip_body]
743 fn from(fd: OwnedFd) -> process::ChildStdin {
744 let pipe = ChildPipe::from_inner(fd);
745 process::ChildStdin::from_inner(pipe)
746 }
747}
748
749#[stable(feature = "io_safety", since = "1.63.0")]
750impl AsFd for crate::process::ChildStdout {
751 #[inline]
752 #[rustdoc_skip_body]
753 fn as_fd(&self) -> BorrowedFd<'_> {
754 self.as_inner().as_fd()
755 }
756}
757
758#[stable(feature = "io_safety", since = "1.63.0")]
759impl From<crate::process::ChildStdout> for OwnedFd {
760 /// Takes ownership of a [`ChildStdout`](crate::process::ChildStdout)'s file descriptor.
761 #[inline]
762 #[rustdoc_skip_body]
763 fn from(child_stdout: crate::process::ChildStdout) -> OwnedFd {
764 child_stdout.into_inner().into_inner()
765 }
766}
767
768/// Creates a `ChildStdout` from the provided `OwnedFd`.
769///
770/// The provided file descriptor must point to a pipe
771/// with the `CLOEXEC` flag set.
772#[stable(feature = "child_stream_from_fd", since = "1.74.0")]
773impl From<OwnedFd> for process::ChildStdout {
774 #[inline]
775 #[rustdoc_skip_body]
776 fn from(fd: OwnedFd) -> process::ChildStdout {
777 let pipe = ChildPipe::from_inner(fd);
778 process::ChildStdout::from_inner(pipe)
779 }
780}
781
782#[stable(feature = "io_safety", since = "1.63.0")]
783impl AsFd for crate::process::ChildStderr {
784 #[inline]
785 #[rustdoc_skip_body]
786 fn as_fd(&self) -> BorrowedFd<'_> {
787 self.as_inner().as_fd()
788 }
789}
790
791#[stable(feature = "io_safety", since = "1.63.0")]
792impl From<crate::process::ChildStderr> for OwnedFd {
793 /// Takes ownership of a [`ChildStderr`](crate::process::ChildStderr)'s file descriptor.
794 #[inline]
795 #[rustdoc_skip_body]
796 fn from(child_stderr: crate::process::ChildStderr) -> OwnedFd {
797 child_stderr.into_inner().into_inner()
798 }
799}
800
801/// Creates a `ChildStderr` from the provided `OwnedFd`.
802///
803/// The provided file descriptor must point to a pipe
804/// with the `CLOEXEC` flag set.
805#[stable(feature = "child_stream_from_fd", since = "1.74.0")]
806impl From<OwnedFd> for process::ChildStderr {
807 #[inline]
808 #[rustdoc_skip_body]
809 fn from(fd: OwnedFd) -> process::ChildStderr {
810 let pipe = ChildPipe::from_inner(fd);
811 process::ChildStderr::from_inner(pipe)
812 }
813}
814
815/// Returns the OS-assigned process identifier associated with this process's parent.
816///
817/// # Example
818///
819#[cfg_attr(target_family = "unix", doc = "```")]
820#[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
821/// use std::os::unix::process;
822/// let parent = process::parent_id();
823/// println!("The parent process has ID {}", parent);
824/// ```
825#[must_use]
826#[stable(feature = "unix_ppid", since = "1.27.0")]
827pub fn parent_id() -> u32 {
828 crate::sys::process::getppid()
829}