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 cfg_if::cfg_if;
8
9use crate::ffi::OsStr;
10use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd};
11use crate::path::Path;
12use crate::sealed::Sealed;
13use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
14use crate::{io, process, sys};
15
16cfg_if! {
17 if #[cfg(any(target_os = "vxworks", target_os = "espidf", target_os = "horizon", target_os = "vita"))] {
18 type UserId = u16;
19 type GroupId = u16;
20 } else if #[cfg(target_os = "nto")] {
21 // Both IDs are signed, see `sys/target_nto.h` of the QNX Neutrino SDP.
22 // Only positive values should be used, see e.g.
23 // https://www.qnx.com/developers/docs/7.1/#com.qnx.doc.neutrino.lib_ref/topic/s/setuid.html
24 type UserId = i32;
25 type GroupId = i32;
26 } else {
27 type UserId = u32;
28 type GroupId = u32;
29 }
30}
31
32/// Unix-specific extensions to the [`process::Command`] builder.
33///
34/// This trait is sealed: it cannot be implemented outside the standard library.
35/// This is so that future additional methods are not breaking changes.
36#[stable(feature = "rust1", since = "1.0.0")]
37pub trait CommandExt: Sealed {
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 /// For further details refer to the [POSIX fork() specification]
84 /// and the equivalent documentation for any targeted
85 /// platform, especially the requirements around *async-signal-safety*.
86 ///
87 /// This also means that all resources such as file descriptors and
88 /// memory-mapped regions got duplicated. It is your responsibility to make
89 /// sure that the closure does not violate library invariants by making
90 /// invalid use of these duplicates.
91 ///
92 /// Panicking in the closure is safe only if all the format arguments for the
93 /// panic message can be safely formatted; this is because although
94 /// `Command` calls [`std::panic::always_abort`](crate::panic::always_abort)
95 /// before calling the pre_exec hook, panic will still try to format the
96 /// panic message.
97 ///
98 /// When this closure is run, aspects such as the stdio file descriptors and
99 /// working directory have successfully been changed, so output to these
100 /// locations might not appear where intended.
101 ///
102 /// [POSIX fork() specification]:
103 /// https://pubs.opengroup.org/onlinepubs/9699919799/functions/fork.html
104 /// [`std::env`]: mod@crate::env
105 #[stable(feature = "process_pre_exec", since = "1.34.0")]
106 unsafe fn pre_exec<F>(&mut self, f: F) -> &mut process::Command
107 where
108 F: FnMut() -> io::Result<()> + Send + Sync + 'static;
109
110 /// Schedules a closure to be run just before the `exec` function is
111 /// invoked.
112 ///
113 /// `before_exec` used to be a safe method, but it needs to be unsafe since the closure may only
114 /// perform operations that are *async-signal-safe*. Hence it got deprecated in favor of the
115 /// unsafe [`pre_exec`]. Meanwhile, Rust gained the ability to make an existing safe method
116 /// fully unsafe in a new edition, which is how `before_exec` became `unsafe`. It still also
117 /// remains deprecated; `pre_exec` should be used instead.
118 ///
119 /// [`pre_exec`]: CommandExt::pre_exec
120 #[stable(feature = "process_exec", since = "1.15.0")]
121 #[deprecated(since = "1.37.0", note = "should be unsafe, use `pre_exec` instead")]
122 #[rustc_deprecated_safe_2024(audit_that = "the closure is async-signal-safe")]
123 unsafe fn before_exec<F>(&mut self, f: F) -> &mut process::Command
124 where
125 F: FnMut() -> io::Result<()> + Send + Sync + 'static,
126 {
127 unsafe { self.pre_exec(f) }
128 }
129
130 /// Performs all the required setup by this `Command`, followed by calling
131 /// the `execvp` syscall.
132 ///
133 /// On success this function will not return, and otherwise it will return
134 /// an error indicating why the exec (or another part of the setup of the
135 /// `Command`) failed.
136 ///
137 /// `exec` not returning has the same implications as calling
138 /// [`process::exit`] – no destructors on the current stack or any other
139 /// thread’s stack will be run. Therefore, it is recommended to only call
140 /// `exec` at a point where it is fine to not run any destructors. Note,
141 /// that the `execvp` syscall independently guarantees that all memory is
142 /// freed and all file descriptors with the `CLOEXEC` option (set by default
143 /// on all file descriptors opened by the standard library) are closed.
144 ///
145 /// This function, unlike `spawn`, will **not** `fork` the process to create
146 /// a new child. Like spawn, however, the default behavior for the stdio
147 /// descriptors will be to inherit them from the current process.
148 ///
149 /// # Notes
150 ///
151 /// The process may be in a "broken state" if this function returns in
152 /// error. For example the working directory, environment variables, signal
153 /// handling settings, various user/group information, or aspects of stdio
154 /// file descriptors may have changed. If a "transactional spawn" is
155 /// required to gracefully handle errors it is recommended to use the
156 /// cross-platform `spawn` instead.
157 #[stable(feature = "process_exec2", since = "1.9.0")]
158 #[must_use]
159 fn exec(&mut self) -> io::Error;
160
161 /// Set executable argument
162 ///
163 /// Set the first process argument, `argv[0]`, to something other than the
164 /// default executable path.
165 #[stable(feature = "process_set_argv0", since = "1.45.0")]
166 fn arg0<S>(&mut self, arg: S) -> &mut process::Command
167 where
168 S: AsRef<OsStr>;
169
170 /// Sets the process group ID (PGID) of the child process. Equivalent to a
171 /// `setpgid` call in the child process, but may be more efficient.
172 ///
173 /// Process groups determine which processes receive signals.
174 ///
175 /// # Examples
176 ///
177 /// Pressing Ctrl-C in a terminal will send SIGINT to all processes in
178 /// the current foreground process group. By spawning the `sleep`
179 /// subprocess in a new process group, it will not receive SIGINT from the
180 /// terminal.
181 ///
182 /// The parent process could install a signal handler and manage the
183 /// subprocess on its own terms.
184 ///
185 /// A process group ID of 0 will use the process ID as the PGID.
186 ///
187 /// ```no_run
188 /// use std::process::Command;
189 /// use std::os::unix::process::CommandExt;
190 ///
191 /// Command::new("sleep")
192 /// .arg("10")
193 /// .process_group(0)
194 /// .spawn()?
195 /// .wait()?;
196 /// #
197 /// # Ok::<_, Box<dyn std::error::Error>>(())
198 /// ```
199 #[stable(feature = "process_set_process_group", since = "1.64.0")]
200 fn process_group(&mut self, pgroup: i32) -> &mut process::Command;
201
202 /// Set the root of the child process. This calls `chroot` in the child process before executing
203 /// the command.
204 ///
205 /// This happens before changing to the directory specified with
206 /// [`process::Command::current_dir`], and that directory will be relative to the new root.
207 ///
208 /// If no directory has been specified with [`process::Command::current_dir`], this will set the
209 /// directory to `/`, to avoid leaving the current directory outside the chroot. (This is an
210 /// intentional difference from the underlying `chroot` system call.)
211 #[unstable(feature = "process_chroot", issue = "141298")]
212 fn chroot<P: AsRef<Path>>(&mut self, dir: P) -> &mut process::Command;
213
214 #[unstable(feature = "process_setsid", issue = "105376")]
215 fn setsid(&mut self, setsid: bool) -> &mut process::Command;
216}
217
218#[stable(feature = "rust1", since = "1.0.0")]
219impl CommandExt for process::Command {
220 fn uid(&mut self, id: UserId) -> &mut process::Command {
221 self.as_inner_mut().uid(id);
222 self
223 }
224
225 fn gid(&mut self, id: GroupId) -> &mut process::Command {
226 self.as_inner_mut().gid(id);
227 self
228 }
229
230 fn groups(&mut self, groups: &[GroupId]) -> &mut process::Command {
231 self.as_inner_mut().groups(groups);
232 self
233 }
234
235 unsafe fn pre_exec<F>(&mut self, f: F) -> &mut process::Command
236 where
237 F: FnMut() -> io::Result<()> + Send + Sync + 'static,
238 {
239 self.as_inner_mut().pre_exec(Box::new(f));
240 self
241 }
242
243 fn exec(&mut self) -> io::Error {
244 // NOTE: This may *not* be safe to call after `libc::fork`, because it
245 // may allocate. That may be worth fixing at some point in the future.
246 self.as_inner_mut().exec(sys::process::Stdio::Inherit)
247 }
248
249 fn arg0<S>(&mut self, arg: S) -> &mut process::Command
250 where
251 S: AsRef<OsStr>,
252 {
253 self.as_inner_mut().set_arg_0(arg.as_ref());
254 self
255 }
256
257 fn process_group(&mut self, pgroup: i32) -> &mut process::Command {
258 self.as_inner_mut().pgroup(pgroup);
259 self
260 }
261
262 fn chroot<P: AsRef<Path>>(&mut self, dir: P) -> &mut process::Command {
263 self.as_inner_mut().chroot(dir.as_ref());
264 self
265 }
266
267 fn setsid(&mut self, setsid: bool) -> &mut process::Command {
268 self.as_inner_mut().setsid(setsid);
269 self
270 }
271}
272
273/// Unix-specific extensions to [`process::ExitStatus`] and
274/// [`ExitStatusError`](process::ExitStatusError).
275///
276/// On Unix, `ExitStatus` **does not necessarily represent an exit status**, as
277/// passed to the `_exit` system call or returned by
278/// [`ExitStatus::code()`](crate::process::ExitStatus::code). It represents **any wait status**
279/// as returned by one of the `wait` family of system
280/// calls.
281///
282/// A Unix wait status (a Rust `ExitStatus`) can represent a Unix exit status, but can also
283/// represent other kinds of process event.
284///
285/// This trait is sealed: it cannot be implemented outside the standard library.
286/// This is so that future additional methods are not breaking changes.
287#[stable(feature = "rust1", since = "1.0.0")]
288pub trait ExitStatusExt: Sealed {
289 /// Creates a new `ExitStatus` or `ExitStatusError` from the raw underlying integer status
290 /// value from `wait`
291 ///
292 /// The value should be a **wait status, not an exit status**.
293 ///
294 /// # Panics
295 ///
296 /// Panics on an attempt to make an `ExitStatusError` from a wait status of `0`.
297 ///
298 /// Making an `ExitStatus` always succeeds and never panics.
299 #[stable(feature = "exit_status_from", since = "1.12.0")]
300 fn from_raw(raw: i32) -> Self;
301
302 /// If the process was terminated by a signal, returns that signal.
303 ///
304 /// In other words, if `WIFSIGNALED`, this returns `WTERMSIG`.
305 #[stable(feature = "rust1", since = "1.0.0")]
306 fn signal(&self) -> Option<i32>;
307
308 /// If the process was terminated by a signal, says whether it dumped core.
309 #[stable(feature = "unix_process_wait_more", since = "1.58.0")]
310 fn core_dumped(&self) -> bool;
311
312 /// If the process was stopped by a signal, returns that signal.
313 ///
314 /// In other words, if `WIFSTOPPED`, this returns `WSTOPSIG`. This is only possible if the status came from
315 /// a `wait` system call which was passed `WUNTRACED`, and was then converted into an `ExitStatus`.
316 #[stable(feature = "unix_process_wait_more", since = "1.58.0")]
317 fn stopped_signal(&self) -> Option<i32>;
318
319 /// Whether the process was continued from a stopped status.
320 ///
321 /// Ie, `WIFCONTINUED`. This is only possible if the status came from a `wait` system call
322 /// which was passed `WCONTINUED`, and was then converted into an `ExitStatus`.
323 #[stable(feature = "unix_process_wait_more", since = "1.58.0")]
324 fn continued(&self) -> bool;
325
326 /// Returns the underlying raw `wait` status.
327 ///
328 /// The returned integer is a **wait status, not an exit status**.
329 #[stable(feature = "unix_process_wait_more", since = "1.58.0")]
330 fn into_raw(self) -> i32;
331}
332
333#[stable(feature = "rust1", since = "1.0.0")]
334impl ExitStatusExt for process::ExitStatus {
335 fn from_raw(raw: i32) -> Self {
336 process::ExitStatus::from_inner(From::from(raw))
337 }
338
339 fn signal(&self) -> Option<i32> {
340 self.as_inner().signal()
341 }
342
343 fn core_dumped(&self) -> bool {
344 self.as_inner().core_dumped()
345 }
346
347 fn stopped_signal(&self) -> Option<i32> {
348 self.as_inner().stopped_signal()
349 }
350
351 fn continued(&self) -> bool {
352 self.as_inner().continued()
353 }
354
355 fn into_raw(self) -> i32 {
356 self.as_inner().into_raw().into()
357 }
358}
359
360#[unstable(feature = "exit_status_error", issue = "84908")]
361impl ExitStatusExt for process::ExitStatusError {
362 fn from_raw(raw: i32) -> Self {
363 process::ExitStatus::from_raw(raw)
364 .exit_ok()
365 .expect_err("<ExitStatusError as ExitStatusExt>::from_raw(0) but zero is not an error")
366 }
367
368 fn signal(&self) -> Option<i32> {
369 self.into_status().signal()
370 }
371
372 fn core_dumped(&self) -> bool {
373 self.into_status().core_dumped()
374 }
375
376 fn stopped_signal(&self) -> Option<i32> {
377 self.into_status().stopped_signal()
378 }
379
380 fn continued(&self) -> bool {
381 self.into_status().continued()
382 }
383
384 fn into_raw(self) -> i32 {
385 self.into_status().into_raw()
386 }
387}
388
389#[unstable(feature = "unix_send_signal", issue = "141975")]
390pub trait ChildExt: Sealed {
391 /// Sends a signal to a child process.
392 ///
393 /// # Errors
394 ///
395 /// This function will return an error if the signal is invalid. The integer values associated
396 /// with signals are implementation-specific, so it's encouraged to use a crate that provides
397 /// posix bindings.
398 ///
399 /// # Examples
400 ///
401 /// ```rust
402 /// #![feature(unix_send_signal)]
403 ///
404 /// use std::{io, os::unix::process::ChildExt, process::{Command, Stdio}};
405 ///
406 /// use libc::SIGTERM;
407 ///
408 /// fn main() -> io::Result<()> {
409 /// let child = Command::new("cat").stdin(Stdio::piped()).spawn()?;
410 /// child.send_signal(SIGTERM)?;
411 /// Ok(())
412 /// }
413 /// ```
414 fn send_signal(&self, signal: i32) -> io::Result<()>;
415}
416
417#[unstable(feature = "unix_send_signal", issue = "141975")]
418impl ChildExt for process::Child {
419 fn send_signal(&self, signal: i32) -> io::Result<()> {
420 self.handle.send_signal(signal)
421 }
422}
423
424#[stable(feature = "process_extensions", since = "1.2.0")]
425impl FromRawFd for process::Stdio {
426 #[inline]
427 unsafe fn from_raw_fd(fd: RawFd) -> process::Stdio {
428 let fd = sys::fd::FileDesc::from_raw_fd(fd);
429 let io = sys::process::Stdio::Fd(fd);
430 process::Stdio::from_inner(io)
431 }
432}
433
434#[stable(feature = "io_safety", since = "1.63.0")]
435impl From<OwnedFd> for process::Stdio {
436 /// Takes ownership of a file descriptor and returns a [`Stdio`](process::Stdio)
437 /// that can attach a stream to it.
438 #[inline]
439 fn from(fd: OwnedFd) -> process::Stdio {
440 let fd = sys::fd::FileDesc::from_inner(fd);
441 let io = sys::process::Stdio::Fd(fd);
442 process::Stdio::from_inner(io)
443 }
444}
445
446#[stable(feature = "process_extensions", since = "1.2.0")]
447impl AsRawFd for process::ChildStdin {
448 #[inline]
449 fn as_raw_fd(&self) -> RawFd {
450 self.as_inner().as_raw_fd()
451 }
452}
453
454#[stable(feature = "process_extensions", since = "1.2.0")]
455impl AsRawFd for process::ChildStdout {
456 #[inline]
457 fn as_raw_fd(&self) -> RawFd {
458 self.as_inner().as_raw_fd()
459 }
460}
461
462#[stable(feature = "process_extensions", since = "1.2.0")]
463impl AsRawFd for process::ChildStderr {
464 #[inline]
465 fn as_raw_fd(&self) -> RawFd {
466 self.as_inner().as_raw_fd()
467 }
468}
469
470#[stable(feature = "into_raw_os", since = "1.4.0")]
471impl IntoRawFd for process::ChildStdin {
472 #[inline]
473 fn into_raw_fd(self) -> RawFd {
474 self.into_inner().into_inner().into_raw_fd()
475 }
476}
477
478#[stable(feature = "into_raw_os", since = "1.4.0")]
479impl IntoRawFd for process::ChildStdout {
480 #[inline]
481 fn into_raw_fd(self) -> RawFd {
482 self.into_inner().into_inner().into_raw_fd()
483 }
484}
485
486#[stable(feature = "into_raw_os", since = "1.4.0")]
487impl IntoRawFd for process::ChildStderr {
488 #[inline]
489 fn into_raw_fd(self) -> RawFd {
490 self.into_inner().into_inner().into_raw_fd()
491 }
492}
493
494#[stable(feature = "io_safety", since = "1.63.0")]
495impl AsFd for crate::process::ChildStdin {
496 #[inline]
497 fn as_fd(&self) -> BorrowedFd<'_> {
498 self.as_inner().as_fd()
499 }
500}
501
502#[stable(feature = "io_safety", since = "1.63.0")]
503impl From<crate::process::ChildStdin> for OwnedFd {
504 /// Takes ownership of a [`ChildStdin`](crate::process::ChildStdin)'s file descriptor.
505 #[inline]
506 fn from(child_stdin: crate::process::ChildStdin) -> OwnedFd {
507 child_stdin.into_inner().into_inner().into_inner()
508 }
509}
510
511/// Creates a `ChildStdin` from the provided `OwnedFd`.
512///
513/// The provided file descriptor must point to a pipe
514/// with the `CLOEXEC` flag set.
515#[stable(feature = "child_stream_from_fd", since = "1.74.0")]
516impl From<OwnedFd> for process::ChildStdin {
517 #[inline]
518 fn from(fd: OwnedFd) -> process::ChildStdin {
519 let fd = sys::fd::FileDesc::from_inner(fd);
520 let pipe = sys::pipe::AnonPipe::from_inner(fd);
521 process::ChildStdin::from_inner(pipe)
522 }
523}
524
525#[stable(feature = "io_safety", since = "1.63.0")]
526impl AsFd for crate::process::ChildStdout {
527 #[inline]
528 fn as_fd(&self) -> BorrowedFd<'_> {
529 self.as_inner().as_fd()
530 }
531}
532
533#[stable(feature = "io_safety", since = "1.63.0")]
534impl From<crate::process::ChildStdout> for OwnedFd {
535 /// Takes ownership of a [`ChildStdout`](crate::process::ChildStdout)'s file descriptor.
536 #[inline]
537 fn from(child_stdout: crate::process::ChildStdout) -> OwnedFd {
538 child_stdout.into_inner().into_inner().into_inner()
539 }
540}
541
542/// Creates a `ChildStdout` from the provided `OwnedFd`.
543///
544/// The provided file descriptor must point to a pipe
545/// with the `CLOEXEC` flag set.
546#[stable(feature = "child_stream_from_fd", since = "1.74.0")]
547impl From<OwnedFd> for process::ChildStdout {
548 #[inline]
549 fn from(fd: OwnedFd) -> process::ChildStdout {
550 let fd = sys::fd::FileDesc::from_inner(fd);
551 let pipe = sys::pipe::AnonPipe::from_inner(fd);
552 process::ChildStdout::from_inner(pipe)
553 }
554}
555
556#[stable(feature = "io_safety", since = "1.63.0")]
557impl AsFd for crate::process::ChildStderr {
558 #[inline]
559 fn as_fd(&self) -> BorrowedFd<'_> {
560 self.as_inner().as_fd()
561 }
562}
563
564#[stable(feature = "io_safety", since = "1.63.0")]
565impl From<crate::process::ChildStderr> for OwnedFd {
566 /// Takes ownership of a [`ChildStderr`](crate::process::ChildStderr)'s file descriptor.
567 #[inline]
568 fn from(child_stderr: crate::process::ChildStderr) -> OwnedFd {
569 child_stderr.into_inner().into_inner().into_inner()
570 }
571}
572
573/// Creates a `ChildStderr` from the provided `OwnedFd`.
574///
575/// The provided file descriptor must point to a pipe
576/// with the `CLOEXEC` flag set.
577#[stable(feature = "child_stream_from_fd", since = "1.74.0")]
578impl From<OwnedFd> for process::ChildStderr {
579 #[inline]
580 fn from(fd: OwnedFd) -> process::ChildStderr {
581 let fd = sys::fd::FileDesc::from_inner(fd);
582 let pipe = sys::pipe::AnonPipe::from_inner(fd);
583 process::ChildStderr::from_inner(pipe)
584 }
585}
586
587/// Returns the OS-assigned process identifier associated with this process's parent.
588#[must_use]
589#[stable(feature = "unix_ppid", since = "1.27.0")]
590pub fn parent_id() -> u32 {
591 crate::sys::os::getppid()
592}