Skip to main content

job_limits/
lib.rs

1//! Put a memory limit on a child process, and clean up the whole process tree when a [`Guard`] is dropped.
2//!
3//! It works the same way on unix and Windows.
4//!
5//! | | unix | Windows |
6//! |---|---|---|
7//! | Memory limit | `setrlimit(RLIMIT_AS)` before the child starts | `PROCESS_MEMORY` of a Job Object |
8//! | Cleanup | The child gets its own process group; dropping the `Guard` sends `SIGKILL` to the whole group | `KILL_ON_JOB_CLOSE` of a Job Object |
9//!
10//! ```no_run
11//! use std::process::Command;
12//!
13//! let limits = job_limits::Limits::new().process_memory(1 << 30);
14//! let (mut child, guard) = limits.spawn(&mut Command::new("my-tool"))?;
15//! child.wait()?;
16//! drop(guard); // ends any grandchildren left behind
17//! # Ok::<(), std::io::Error>(())
18//! ```
19//!
20//! # What the limit means
21//!
22//! The limit applies to the memory one child process can allocate. Once it is exceeded, allocations fail
23//! (whether the child then dies is up to the child).
24//! Each OS counts differently: address space on unix, commit charge on Windows.
25//! The same value therefore does not give exactly the same behavior.
26//!
27//! - Linux enforces the limit. macOS may not enforce `RLIMIT_AS`. A failure to set the limit is ignored
28//!   (the child runs without it).
29//! - On Windows, the limit is not in effect for the short time between starting the child and putting it
30//!   into the Job.
31//! - On unix, if the child ends before the `Guard` is dropped and its process group becomes empty, the
32//!   process ID may be reused by an unrelated group, which the `Guard` would then kill. Dropping the
33//!   `Guard` right after `wait`ing for the child avoids this in practice.
34
35#![cfg_attr(docsrs, feature(doc_cfg))]
36
37#[cfg(not(any(unix, windows)))]
38compile_error!("job-limits supports only unix and Windows");
39
40#[cfg(unix)]
41mod unix;
42#[cfg(unix)]
43use unix as sys;
44
45#[cfg(windows)]
46mod windows;
47#[cfg(windows)]
48use windows as sys;
49
50use std::io;
51use std::process::{Child, Command};
52
53/// Limits to put on a child process.
54#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
55pub struct Limits {
56    process_memory: Option<u64>,
57}
58
59impl Limits {
60    /// No limits.
61    pub fn new() -> Self {
62        Self::default()
63    }
64
65    /// The memory limit of one child process, in bytes. 0 is not allowed.
66    pub fn process_memory(mut self, bytes: u64) -> Self {
67        self.process_memory = Some(bytes);
68        self
69    }
70
71    fn check(&self) -> io::Result<()> {
72        if self.process_memory == Some(0) {
73            return Err(io::Error::new(
74                io::ErrorKind::InvalidInput,
75                "the memory limit must not be 0",
76            ));
77        }
78        Ok(())
79    }
80
81    /// Spawns a child process with the limits applied. Dropping the returned [`Guard`] ends the child and its descendants.
82    ///
83    /// If the limits cannot be applied, the child is killed and an error is returned.
84    pub fn spawn(&self, command: &mut Command) -> io::Result<(Child, Guard)> {
85        self.check()?;
86        sys::prepare(self, command);
87        let mut child = command.spawn()?;
88        match sys::attach(self, child.id(), sys::raw(&child)) {
89            Ok(inner) => Ok((child, Guard(inner))),
90            Err(e) => {
91                let _ = child.kill();
92                let _ = child.wait();
93                Err(e)
94            }
95        }
96    }
97
98    /// The tokio version of [`spawn`](Self::spawn).
99    #[cfg(feature = "tokio")]
100    #[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
101    pub fn spawn_tokio(
102        &self,
103        command: &mut tokio::process::Command,
104    ) -> io::Result<(tokio::process::Child, Guard)> {
105        self.check()?;
106        sys::prepare(self, command.as_std_mut());
107        let mut child = command.spawn()?;
108        let attached = match child.id() {
109            Some(id) => sys::raw_tokio(&child).and_then(|raw| sys::attach(self, id, raw)),
110            None => Err(io::Error::other("the child process has already ended")),
111        };
112        match attached {
113            Ok(inner) => Ok((child, Guard(inner))),
114            Err(e) => {
115                // `start_kill` is enough here; the caller reaps the child when it drops it
116                let _ = child.start_kill();
117                Err(e)
118            }
119        }
120    }
121}
122
123/// Cleans up a child process. Dropping it ends the child and its descendants.
124///
125/// It is fine for the child to have ended already.
126#[derive(Debug)]
127pub struct Guard(#[allow(dead_code)] sys::Guard);