Skip to content

Commit bc6cf01

Browse files
feat: pid_open
1 parent a394a7e commit bc6cf01

File tree

3 files changed

+31
-3
lines changed

3 files changed

+31
-3
lines changed

changelog/1868.added.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1-
Added `pidfd_getfd` on Linux.
1+
- Added `pidfd_getfd` on Linux.
2+
- Added `pid_open` on Linux.

src/sys/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -224,5 +224,5 @@ feature! {
224224
pub mod timer;
225225
}
226226

227-
#[cfg(target_os = "linux")]
227+
#[cfg(all(target_os = "linux", feature = "process"))]
228228
pub mod pidfd;

src/sys/pidfd.rs

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
//! pidfd related functionality
22
33
use crate::errno::Errno;
4+
use crate::unistd::Pid;
45
use crate::Result;
56
use std::convert::TryFrom;
67
use std::os::unix::io::{AsFd, AsRawFd, FromRawFd, OwnedFd};
@@ -42,4 +43,30 @@ pub fn pidfd_getfd<PFd: AsFd, TFd: AsFd>(
4243
}
4344
_ => unreachable!(),
4445
}
45-
}
46+
}
47+
48+
/// Creates a file descriptor that refers to the process whose PID is specified in `pid`. The file
49+
/// descriptor is returned as the function result; the close-on-exec flag is set on the file
50+
/// descriptor.
51+
///
52+
/// If `nonblock == true` returns a nonblocking file descriptor. If the process
53+
/// referred to by the file descriptor has not yet terminated,
54+
/// then an attempt to wait on the file descriptor using
55+
/// waitid(2) will immediately return the error EAGAIN rather
56+
/// than blocking.
57+
pub fn pid_open(pid: Pid, nonblock: bool) -> Result<OwnedFd> {
58+
#[allow(clippy::useless_conversion)] // Not useless on all OSes
59+
match unsafe {
60+
libc::syscall(
61+
libc::SYS_pidfd_open,
62+
pid,
63+
if nonblock { libc::PIDFD_NONBLOCK } else { 0 },
64+
)
65+
} {
66+
-1 => Err(Errno::last()),
67+
fd @ 0.. => {
68+
Ok(unsafe { OwnedFd::from_raw_fd(i32::try_from(fd).unwrap()) })
69+
}
70+
_ => unreachable!(),
71+
}
72+
}

0 commit comments

Comments
 (0)