rustix/pid.rs
1//! The `Pid` type.
2
3#![allow(unsafe_code)]
4
5use core::num::NonZeroI32;
6
7/// A process identifier as a raw integer.
8pub type RawPid = i32;
9
10/// `pid_t`—A non-zero Unix process ID.
11///
12/// This is a pid, and not a pidfd. It is not a file descriptor, and the
13/// process it refers to could disappear at any time and be replaced by
14/// another, unrelated, process.
15///
16/// On Linux, `Pid` values are also used to identify threads.
17#[repr(transparent)]
18#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)]
19pub struct Pid(NonZeroI32);
20
21impl Pid {
22 /// A `Pid` corresponding to the init process (pid 1).
23 pub const INIT: Self = Self(match NonZeroI32::new(1) {
24 Some(n) => n,
25 None => panic!("unreachable"),
26 });
27
28 /// Converts a `RawPid` into a `Pid`.
29 ///
30 /// Returns `Some` for positive values, and `None` for zero values.
31 ///
32 /// This is safe because a `Pid` is a number without any guarantees for the
33 /// kernel. Non-child `Pid`s are always racy for any syscalls, but can only
34 /// cause logic errors. If you want race-free access to or control of
35 /// non-child processes, please consider other mechanisms like [pidfd] on
36 /// Linux.
37 ///
38 /// Passing a negative number doesn't invoke undefined behavior, but it
39 /// may cause unexpected behavior.
40 ///
41 /// [pidfd]: https://man7.org/linux/man-pages/man2/pidfd_open.2.html
42 #[inline]
43 pub const fn from_raw(raw: RawPid) -> Option<Self> {
44 debug_assert!(raw >= 0);
45 match NonZeroI32::new(raw) {
46 Some(non_zero) => Some(Self(non_zero)),
47 None => None,
48 }
49 }
50
51 /// Converts a known positive `RawPid` into a `Pid`.
52 ///
53 /// Passing a negative number doesn't invoke undefined behavior, but it
54 /// may cause unexpected behavior.
55 ///
56 /// # Safety
57 ///
58 /// The caller must guarantee `raw` is non-zero.
59 #[inline]
60 pub const unsafe fn from_raw_unchecked(raw: RawPid) -> Self {
61 debug_assert!(raw > 0);
62 Self(NonZeroI32::new_unchecked(raw))
63 }
64
65 /// Creates a `Pid` holding the ID of the given child process.
66 #[cfg(feature = "std")]
67 #[inline]
68 pub fn from_child(child: &std::process::Child) -> Self {
69 let id = child.id();
70 // SAFETY: We know the returned ID is valid because it came directly
71 // from an OS API.
72 unsafe { Self::from_raw_unchecked(id as i32) }
73 }
74
75 /// Converts a `Pid` into a `NonZeroI32`.
76 #[inline]
77 pub const fn as_raw_nonzero(self) -> NonZeroI32 {
78 self.0
79 }
80
81 /// Converts an `Option<Pid>` into a `RawPid`.
82 #[inline]
83 pub const fn as_raw(pid: Option<Self>) -> RawPid {
84 match pid {
85 Some(pid) => pid.0.get(),
86 None => 0,
87 }
88 }
89
90 /// Test whether this pid represents the init process ([`Pid::INIT`]).
91 #[inline]
92 pub const fn is_init(self) -> bool {
93 self.0.get() == Self::INIT.0.get()
94 }
95}
96
97#[cfg(test)]
98mod tests {
99 use super::*;
100
101 #[test]
102 fn test_sizes() {
103 use core::mem::transmute;
104
105 assert_eq_size!(RawPid, NonZeroI32);
106 assert_eq_size!(RawPid, Pid);
107 assert_eq_size!(RawPid, Option<Pid>);
108
109 // Rustix doesn't depend on `Option<Pid>` matching the ABI of a raw integer
110 // for correctness, but it should work nonetheless.
111 const_assert_eq!(0 as RawPid, unsafe {
112 transmute::<Option<Pid>, RawPid>(None)
113 });
114 const_assert_eq!(4567 as RawPid, unsafe {
115 transmute::<Option<Pid>, RawPid>(Some(Pid::from_raw_unchecked(4567)))
116 });
117 }
118
119 #[test]
120 fn test_ctors() {
121 use std::num::NonZeroI32;
122 assert!(Pid::from_raw(0).is_none());
123 assert_eq!(
124 Pid::from_raw(77).unwrap().as_raw_nonzero(),
125 NonZeroI32::new(77).unwrap()
126 );
127 assert_eq!(Pid::as_raw(Pid::from_raw(77)), 77);
128 }
129
130 #[test]
131 fn test_specials() {
132 assert!(Pid::from_raw(1).unwrap().is_init());
133 assert_eq!(Pid::from_raw(1).unwrap(), Pid::INIT);
134 }
135}