#![allow(unsafe_code)]
use std::io;
use std::os::unix::process::CommandExt;
use std::process::{Child, Command};
use rustix::process::{Pid, Resource, Rlimit, Signal, kill_process_group, setrlimit};
use crate::Limits;
pub(crate) struct Raw;
pub(crate) fn raw(_: &Child) -> Raw {
Raw
}
#[cfg(feature = "tokio")]
pub(crate) fn raw_tokio(_: &tokio::process::Child) -> io::Result<Raw> {
Ok(Raw)
}
pub(crate) fn prepare(limits: &Limits, command: &mut Command) {
command.process_group(0);
if let Some(bytes) = limits.process_memory {
let rlimit = Rlimit {
current: Some(bytes),
maximum: Some(bytes),
};
unsafe {
command.pre_exec(move || {
let _ = setrlimit(Resource::As, rlimit);
Ok(())
});
}
}
}
#[derive(Debug)]
pub(crate) struct Guard(Pid);
pub(crate) fn attach(_: &Limits, pid: u32, _: Raw) -> io::Result<Guard> {
i32::try_from(pid)
.ok()
.and_then(Pid::from_raw)
.map(Guard)
.ok_or_else(|| io::Error::other("the process ID is out of range"))
}
impl Drop for Guard {
fn drop(&mut self) {
let _ = kill_process_group(self.0, Signal::KILL);
}
}