Expand description
Put a memory limit on a child process, and clean up the whole process tree when a Guard is dropped.
It works the same way on unix and Windows.
| unix | Windows | |
|---|---|---|
| Memory limit | setrlimit(RLIMIT_AS) before the child starts | PROCESS_MEMORY of a Job Object |
| 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 |
use std::process::Command;
let limits = job_limits::Limits::new().process_memory(1 << 30);
let (mut child, guard) = limits.spawn(&mut Command::new("my-tool"))?;
child.wait()?;
drop(guard); // ends any grandchildren left behind§What the limit means
The limit applies to the memory one child process can allocate. Once it is exceeded, allocations fail (whether the child then dies is up to the child). Each OS counts differently: address space on unix, commit charge on Windows. The same value therefore does not give exactly the same behavior.
- Linux enforces the limit. macOS may not enforce
RLIMIT_AS. A failure to set the limit is ignored (the child runs without it). - On Windows, the limit is not in effect for the short time between starting the child and putting it into the Job.
- On unix, if the child ends before the
Guardis dropped and its process group becomes empty, the process ID may be reused by an unrelated group, which theGuardwould then kill. Dropping theGuardright afterwaiting for the child avoids this in practice.