Skip to content

Commit 9b34bd2

Browse files
feat: pid_open
1 parent 347e6bc commit 9b34bd2

File tree

3 files changed

+37
-2
lines changed

3 files changed

+37
-2
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ This project adheres to [Semantic Versioning](https://semver.org/).
1313
([#1912](https://github.com/nix-rust/nix/pull/1912))
1414
- Added `pidfd_getfd` on Linux.
1515
([#1868](https://github.com/nix-rust/nix/pull/1868))
16+
- Added `pid_open` on Linux.
17+
([#1868](https://github.com/nix-rust/nix/pull/1868))
1618

1719
### Changed
1820

src/sys/mod.rs

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

230-
#[cfg(target_os = "linux")]
230+
#[cfg(all(target_os = "linux", feature = "process"))]
231231
/// pidfd related functionality
232232
pub mod pidfd;

src/sys/pidfd.rs

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

0 commit comments

Comments
 (0)