#![cfg_attr(docsrs, feature(doc_cfg))]
#[cfg(not(any(unix, windows)))]
compile_error!("job-limits supports only unix and Windows");
#[cfg(unix)]
mod unix;
#[cfg(unix)]
use unix as sys;
#[cfg(windows)]
mod windows;
#[cfg(windows)]
use windows as sys;
use std::io;
use std::process::{Child, Command};
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Limits {
process_memory: Option<u64>,
}
impl Limits {
pub fn new() -> Self {
Self::default()
}
pub fn process_memory(mut self, bytes: u64) -> Self {
self.process_memory = Some(bytes);
self
}
fn check(&self) -> io::Result<()> {
if self.process_memory == Some(0) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"the memory limit must not be 0",
));
}
Ok(())
}
pub fn spawn(&self, command: &mut Command) -> io::Result<(Child, Guard)> {
self.check()?;
sys::prepare(self, command);
let mut child = command.spawn()?;
match sys::attach(self, child.id(), sys::raw(&child)) {
Ok(inner) => Ok((child, Guard(inner))),
Err(e) => {
let _ = child.kill();
let _ = child.wait();
Err(e)
}
}
}
#[cfg(feature = "tokio")]
#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
pub fn spawn_tokio(
&self,
command: &mut tokio::process::Command,
) -> io::Result<(tokio::process::Child, Guard)> {
self.check()?;
sys::prepare(self, command.as_std_mut());
let mut child = command.spawn()?;
let attached = match child.id() {
Some(id) => sys::raw_tokio(&child).and_then(|raw| sys::attach(self, id, raw)),
None => Err(io::Error::other("the child process has already ended")),
};
match attached {
Ok(inner) => Ok((child, Guard(inner))),
Err(e) => {
let _ = child.start_kill();
Err(e)
}
}
}
}
#[derive(Debug)]
pub struct Guard(#[allow(dead_code)] sys::Guard);