job-limits 0.1.0

Memory limits for child processes, and a guard that cleans up the whole process tree (same API on unix and Windows)
Documentation
#![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;

/// Stands in for the process handle that the Windows side needs; unix needs nothing.
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)
}

/// Puts the child in its own process group and applies the limit just before exec.
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),
        };
        // SAFETY: this runs between fork and exec, so it must be async-signal-safe.
        // `setrlimit` only makes a system call; it neither allocates nor takes locks.
        unsafe {
            command.pre_exec(move || {
                // On an OS that cannot enforce the limit (such as macOS), carry on without it
                let _ = setrlimit(Resource::As, rlimit);
                Ok(())
            });
        }
    }
}

/// The child's process group (the group ID is the child's process ID).
#[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);
    }
}