use std::os::fd::{AsFd, OwnedFd};
use super::child::{KillRefusal, OsChild, OsHandle, PeekOutcome, TryObserveOutcome};
use super::{Exit, OsProcess, WaitFor};
use crate::error::Error;
use crate::identity::Kernel;
use crate::signal::{send_pidfd, Sent, Sig};
use crate::wait::exit_only::{self, Reap, Target};
pub(crate) mod fork;
pub(crate) mod open;
pub(crate) struct LinuxProcess<K> {
kernel: K,
pid: Option<u32>,
pidfd: OwnedFd,
}
impl<K> std::fmt::Debug for LinuxProcess<K> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("LinuxProcess")
.field("pid", &self.pid)
.field("pidfd", &self.pidfd)
.finish_non_exhaustive()
}
}
impl<K: Kernel + Send> LinuxProcess<K> {
pub(crate) fn new(kernel: K, pid: Option<u32>, pidfd: OwnedFd) -> Self {
Self { kernel, pid, pidfd }
}
fn target(&self) -> Target<'_> {
Target::pidfd(&self.kernel, self.pidfd.as_fd())
}
}
impl<K: Kernel + Send> OsProcess for LinuxProcess<K> {
fn signal(&self, sig: Sig) -> Result<Sent, Error> {
let sent = send_pidfd(self.pidfd.as_fd(), self.pid, sig);
#[cfg(test)]
crate::send_log::record_by_identity(self.pid.unwrap_or(0), sig.as_libc());
sent.map_err(|e| Error::Io(std::io::Error::from(e)))
}
fn exited(&self) -> Result<Exit<'_>, Error> {
if super::poll::is_readable(self.pidfd.as_fd()).map_err(Error::Io)? {
Ok(Exit::Exited)
} else {
Ok(Exit::Running(WaitFor::Readable(self.pidfd.as_fd())))
}
}
fn os_handle(&self) -> OsHandle<'_> {
self.pidfd.as_fd()
}
}
impl<K: Kernel + Send> OsChild for LinuxProcess<K> {
fn pid(&self) -> Option<u32> {
self.pid
}
fn kernel(&self) -> &dyn Kernel {
&self.kernel
}
fn kill_refusal(&self) -> KillRefusal {
KillRefusal::Permission
}
fn peek(&self) -> Result<PeekOutcome, Error> {
exit_only::linux::peek(&self.target()).map_err(Error::Io)
}
fn try_observe(&self) -> Result<TryObserveOutcome<'_>, Error> {
let pidfd = self.pidfd.as_fd();
let readable = super::poll::is_readable(pidfd).map_err(Error::Io)?;
Ok(match exit_only::linux::peek(&self.target()).map_err(Error::Io)? {
PeekOutcome::Exit(record) => TryObserveOutcome::Exited(record),
PeekOutcome::Foreign(foreign) => TryObserveOutcome::Foreign(foreign),
PeekOutcome::Running if readable => TryObserveOutcome::Recheck,
PeekOutcome::Running => TryObserveOutcome::Running(WaitFor::Readable(pidfd)),
})
}
fn try_reap(&self) -> Result<Reap, Error> {
exit_only::try_reap(&self.target()).map_err(Error::Io)
}
fn exact_consume(&self) -> bool {
true
}
}
#[cfg(test)]
#[path = "linux_tests.rs"]
mod linux_tests;