rustix/
pid.rs

1//! The `Pid` type.
2
3#![allow(unsafe_code)]
4
5use core::{fmt, 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 a `Pid` into a `RawPid`.
82    ///
83    /// This is the same as `self.as_raw_nonzero().get()`.
84    #[inline]
85    pub const fn as_raw_pid(self) -> RawPid {
86        self.0.get()
87    }
88
89    /// Converts an `Option<Pid>` into a `RawPid`.
90    #[inline]
91    pub const fn as_raw(pid: Option<Self>) -> RawPid {
92        match pid {
93            Some(pid) => pid.0.get(),
94            None => 0,
95        }
96    }
97
98    /// Test whether this pid represents the init process ([`Pid::INIT`]).
99    #[inline]
100    pub const fn is_init(self) -> bool {
101        self.0.get() == Self::INIT.0.get()
102    }
103}
104
105impl fmt::Display for Pid {
106    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107        self.0.fmt(f)
108    }
109}
110impl fmt::Binary for Pid {
111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112        self.0.fmt(f)
113    }
114}
115impl fmt::Octal for Pid {
116    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117        self.0.fmt(f)
118    }
119}
120impl fmt::LowerHex for Pid {
121    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122        self.0.fmt(f)
123    }
124}
125impl fmt::UpperHex for Pid {
126    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127        self.0.fmt(f)
128    }
129}
130#[cfg(lower_upper_exp_for_non_zero)]
131impl fmt::LowerExp for Pid {
132    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133        self.0.fmt(f)
134    }
135}
136#[cfg(lower_upper_exp_for_non_zero)]
137impl fmt::UpperExp for Pid {
138    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139        self.0.fmt(f)
140    }
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146
147    #[test]
148    fn test_sizes() {
149        use core::mem::transmute;
150
151        assert_eq_size!(RawPid, NonZeroI32);
152        assert_eq_size!(RawPid, Pid);
153        assert_eq_size!(RawPid, Option<Pid>);
154
155        // Rustix doesn't depend on `Option<Pid>` matching the ABI of a raw integer
156        // for correctness, but it should work nonetheless.
157        const_assert_eq!(0 as RawPid, unsafe {
158            transmute::<Option<Pid>, RawPid>(None)
159        });
160        const_assert_eq!(4567 as RawPid, unsafe {
161            transmute::<Option<Pid>, RawPid>(Some(Pid::from_raw_unchecked(4567)))
162        });
163    }
164
165    #[test]
166    fn test_ctors() {
167        use std::num::NonZeroI32;
168        assert!(Pid::from_raw(0).is_none());
169        assert_eq!(
170            Pid::from_raw(77).unwrap().as_raw_nonzero(),
171            NonZeroI32::new(77).unwrap()
172        );
173        assert_eq!(Pid::from_raw(77).unwrap().as_raw_pid(), 77);
174        assert_eq!(Pid::as_raw(Pid::from_raw(77)), 77);
175    }
176
177    #[test]
178    fn test_specials() {
179        assert!(Pid::from_raw(1).unwrap().is_init());
180        assert_eq!(Pid::from_raw(1).unwrap(), Pid::INIT);
181    }
182}