-
Notifications
You must be signed in to change notification settings - Fork 97
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Use async pid fd instead of blocking waitid to wait for a child proce…
…ss to exit Signed-off-by: Jorge Prendes <[email protected]>
- Loading branch information
Showing
3 changed files
with
48 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,5 @@ | ||
pub mod container; | ||
pub mod metrics; | ||
pub mod stdio; | ||
|
||
mod pid_fd; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
use std::os::fd::{AsFd, FromRawFd as _, OwnedFd, RawFd}; | ||
|
||
use libc::pid_t; | ||
use nix::sys::wait::{waitid, Id, WaitPidFlag, WaitStatus}; | ||
use tokio::io::unix::AsyncFd; | ||
|
||
pub(super) struct PidFd { | ||
fd: OwnedFd, | ||
} | ||
|
||
impl PidFd { | ||
pub(super) fn new(pid: impl Into<pid_t>) -> anyhow::Result<Self> { | ||
use libc::{syscall, SYS_pidfd_open, PIDFD_NONBLOCK}; | ||
let pidfd = unsafe { syscall(SYS_pidfd_open, pid.into(), PIDFD_NONBLOCK) }; | ||
if pidfd == -1 { | ||
return Err(std::io::Error::last_os_error().into()); | ||
} | ||
let fd = unsafe { OwnedFd::from_raw_fd(pidfd as RawFd) }; | ||
Ok(Self { fd }) | ||
} | ||
|
||
pub(super) async fn wait(self) -> std::io::Result<WaitStatus> { | ||
let fd = AsyncFd::new(self.fd)?; | ||
loop { | ||
match waitid(Id::PIDFd(fd.as_fd()), WaitPidFlag::WEXITED | WaitPidFlag::WNOHANG)? { | ||
WaitStatus::StillAlive => { | ||
let _ = fd.readable().await?; | ||
} | ||
status => { | ||
return Ok(status); | ||
} | ||
} | ||
} | ||
} | ||
} |