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 `RawPid`s. Otherwise, returns `None`.
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    /// [pidfd]: https://man7.org/linux/man-pages/man2/pidfd_open.2.html
39    #[inline]
40    pub const fn from_raw(raw: RawPid) -> Option<Self> {
41        match NonZeroI32::new(raw) {
42            Some(non_zero) => Some(Self(non_zero)),
43            None => None,
44        }
45    }
46
47    /// Converts a known positive `RawPid` into a `Pid`.
48    ///
49    /// # Safety
50    ///
51    /// The caller must guarantee `raw` is positive.
52    #[inline]
53    pub const unsafe fn from_raw_unchecked(raw: RawPid) -> Self {
54        debug_assert!(raw > 0);
55        Self(NonZeroI32::new_unchecked(raw))
56    }
57
58    /// Creates a `Pid` holding the ID of the given child process.
59    #[cfg(feature = "std")]
60    #[inline]
61    pub fn from_child(child: &std::process::Child) -> Self {
62        let id = child.id();
63        // SAFETY: We know the returned ID is valid because it came directly
64        // from an OS API.
65        unsafe { Self::from_raw_unchecked(id as i32) }
66    }
67
68    /// Converts a `Pid` into a `NonZeroI32`.
69    #[inline]
70    pub const fn as_raw_nonzero(self) -> NonZeroI32 {
71        self.0
72    }
73
74    /// Converts an `Option<Pid>` into a `RawPid`.
75    #[inline]
76    pub const fn as_raw(pid: Option<Self>) -> RawPid {
77        match pid {
78            Some(pid) => pid.0.get(),
79            None => 0,
80        }
81    }
82
83    /// Test whether this pid represents the init process ([`Pid::INIT`]).
84    #[inline]
85    pub const fn is_init(self) -> bool {
86        self.0.get() == Self::INIT.0.get()
87    }
88}
89
90#[cfg(test)]
91mod tests {
92    use super::*;
93
94    #[test]
95    fn test_sizes() {
96        use core::mem::transmute;
97
98        assert_eq_size!(RawPid, NonZeroI32);
99        assert_eq_size!(RawPid, Pid);
100        assert_eq_size!(RawPid, Option<Pid>);
101
102        // Rustix doesn't depend on `Option<Pid>` matching the ABI of a raw integer
103        // for correctness, but it should work nonetheless.
104        const_assert_eq!(0 as RawPid, unsafe {
105            transmute::<Option<Pid>, RawPid>(None)
106        });
107        const_assert_eq!(4567 as RawPid, unsafe {
108            transmute::<Option<Pid>, RawPid>(Some(Pid::from_raw_unchecked(4567)))
109        });
110    }
111}