std/sys/pal/unix/linux/
pidfd.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
use crate::io;
use crate::os::fd::{AsRawFd, FromRawFd, RawFd};
use crate::sys::cvt;
use crate::sys::pal::unix::fd::FileDesc;
use crate::sys::process::ExitStatus;
use crate::sys_common::{AsInner, FromInner, IntoInner};

#[cfg(test)]
mod tests;

#[derive(Debug)]
pub(crate) struct PidFd(FileDesc);

impl PidFd {
    pub fn kill(&self) -> io::Result<()> {
        cvt(unsafe {
            libc::syscall(
                libc::SYS_pidfd_send_signal,
                self.0.as_raw_fd(),
                libc::SIGKILL,
                crate::ptr::null::<()>(),
                0,
            )
        })
        .map(drop)
    }

    pub fn wait(&self) -> io::Result<ExitStatus> {
        let mut siginfo: libc::siginfo_t = unsafe { crate::mem::zeroed() };
        cvt(unsafe {
            libc::waitid(libc::P_PIDFD, self.0.as_raw_fd() as u32, &mut siginfo, libc::WEXITED)
        })?;
        Ok(ExitStatus::from_waitid_siginfo(siginfo))
    }

    pub fn try_wait(&self) -> io::Result<Option<ExitStatus>> {
        let mut siginfo: libc::siginfo_t = unsafe { crate::mem::zeroed() };

        cvt(unsafe {
            libc::waitid(
                libc::P_PIDFD,
                self.0.as_raw_fd() as u32,
                &mut siginfo,
                libc::WEXITED | libc::WNOHANG,
            )
        })?;
        if unsafe { siginfo.si_pid() } == 0 {
            Ok(None)
        } else {
            Ok(Some(ExitStatus::from_waitid_siginfo(siginfo)))
        }
    }
}

impl AsInner<FileDesc> for PidFd {
    fn as_inner(&self) -> &FileDesc {
        &self.0
    }
}

impl IntoInner<FileDesc> for PidFd {
    fn into_inner(self) -> FileDesc {
        self.0
    }
}

impl FromInner<FileDesc> for PidFd {
    fn from_inner(inner: FileDesc) -> Self {
        Self(inner)
    }
}

impl FromRawFd for PidFd {
    unsafe fn from_raw_fd(fd: RawFd) -> Self {
        Self(FileDesc::from_raw_fd(fd))
    }
}