Forked from s3rvac/limit-virtual-memory-of-subprocess.py
Created
February 8, 2023 07:33
-
-
Save cgarjun/eba222fbce49ac0b85ec07a8a581cf79 to your computer and use it in GitHub Desktop.
Revisions
-
s3rvac created this gist
May 3, 2018 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,27 @@ #!/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()