Skip to content

Commit 84db702

Browse files
feat: pid_open
1 parent a187f89 commit 84db702

File tree

3 files changed

+31
-2
lines changed

3 files changed

+31
-2
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ This project adheres to [Semantic Versioning](https://semver.org/).
1515
([#1966])(https://github.com/nix-rust/nix/pull/1966)
1616
- Added `pidfd_getfd` on Linux.
1717
([#1868](https://github.com/nix-rust/nix/pull/1868))
18+
- Added `pid_open` on Linux.
19+
([#1868](https://github.com/nix-rust/nix/pull/1868))
1820

1921
### Changed
2022

src/sys/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -227,5 +227,5 @@ feature! {
227227
pub mod timer;
228228
}
229229

230-
#[cfg(target_os = "linux")]
230+
#[cfg(all(target_os = "linux", feature = "process"))]
231231
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)