I want to run a binary in Python, but I want to disallow the binary from making new processes. It seems like the standard way to do this is to call setrlimit
through the resource
module, and constrain resource.RLIMIT_NPROC
. However, my attempts have all failed.
Here's a simple example:
foo.py:
import subprocess
import resource
import os
def set_nproc() -> None:
resource.setrlimit(
resource.RLIMIT_NPROC,
(1, 1),
)
if __name__ == '__main__':
subprocess.Popen(['./a.out'], preexec_fn=set_nproc)
foo.c:
#include <unistd.h>
#include <stdlib.h>
int main() {
printf("Running C Program!\n");
int pid = fork();
sleep(10);
return 0;
}
Also, a.out
is the binary produced by compiling foo.c
. Running foo.py
, I'd expect the following to take place:
subprocess.Popen
will spawn a new process. Before running./a.out
, it will run theset_nproc
function, which will set theRLIMIT_NPROC
soft and hard limit to1
.The new process will run the binary
a.out
. The binary will printRunning C Program!
and terminate because the next line tries to spawn a new process, which is not allowed.
It seems like my understanding is not correct because the C program actually terminates to completion (i.e., I do not receive any sort of error). How can I fix this?
Note: I realize that setrlimit
imposes a limit on the user and not the process. Even then, I'd expect an error to take place somewhere here.