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