Skip to content

Instantly share code, notes, and snippets.

@s3rvac
Created May 3, 2018 07:54
Show Gist options
  • Save s3rvac/f97d6cbdfdb15c0a32e7e941f7f4a3fa to your computer and use it in GitHub Desktop.
Save s3rvac/f97d6cbdfdb15c0a32e7e941f7f4a3fa to your computer and use it in GitHub Desktop.
Limits the maximal virtual memory for a subprocess in Python on Linux.
#!/usr/bin/env python3
#
# Limits the maximal virtual memory for a subprocess in Python.
#
# Linux only.
#
import subprocess
import resource
# Maximal virtual memory for subprocesses (in bytes).
MAX_VIRTUAL_MEMORY = 10 * 1024 * 1024 # 10 MB
def limit_virtual_memory():
# The tuple below is of the form (soft limit, hard limit). Limit only
# the soft part so that the limit can be increased later (setting also
# the hard limit would prevent that).
# When the limit cannot be changed, setrlimit() raises ValueError.
resource.setrlimit(resource.RLIMIT_AS, (MAX_VIRTUAL_MEMORY, resource.RLIM_INFINITY))
p = subprocess.Popen(
['ls', '-l', '/'],
# preexec_fn is a callable object that will be called in the child process
# just before the child is executed.
preexec_fn=limit_virtual_memory
)
p.communicate()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment