Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save cgarjun/eba222fbce49ac0b85ec07a8a581cf79 to your computer and use it in GitHub Desktop.

Select an option

Save cgarjun/eba222fbce49ac0b85ec07a8a581cf79 to your computer and use it in GitHub Desktop.

Revisions

  1. @s3rvac s3rvac created this gist May 3, 2018.
    27 changes: 27 additions & 0 deletions limit-virtual-memory-of-subprocess.py
    Original 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()