Leaky subprocess timeout High

If the process doesn't terminate after timeout seconds, a TimeoutExpired exception is raised. Because the child process does not end if the timeout expires, to properly clean up you must explicitly end the child process and finish communication.

Detector ID
python/leaky-subprocess-timeout@v1.0
Category
Common Weakness Enumeration (CWE) external icon
-

Noncompliant example

1def subprocess_timeout_noncompliant():
2    import subprocess
3    process = subprocess.Popen("ls -al",
4                               bufsize=-1,
5                               stdout=subprocess.PIPE,
6                               stderr=subprocess.PIPE)
7    try:
8        # Noncompliant: fails to terminate the child process before
9        # the timeout expires.
10        outs, errs = process.communicate(timeout=15)
11    except subprocess.TimeoutExpired:
12        print("Timed out")

Compliant example

1def subprocess_timeout_compliant():
2    import subprocess
3    process = subprocess.Popen("ls -al",
4                               bufsize=-1,
5                               stdout=subprocess.PIPE,
6                               stderr=subprocess.PIPE)
7    try:
8        # Compliant: makes sure to terminate the child process when
9        # the timeout expires.
10        outs, errs = process.communicate(timeout=15)
11    except subprocess.TimeoutExpired:
12        process.kill()
13        outs, errs = process.communicate()