How to limit program's execution time when using subprocess?
kill, python, subprocess
Solution
do it like so in your command line:
perl -e 'alarm shift @ARGV; exec @ARGV' <timeout> <your_command>
this will run the command `<your_command>` and terminate it in `<timeout>` second.
a dummy example :
# set time out to 5, so that the command will be killed after 5 second
command = ['perl', '-e', "'alarm shift @ARGV; exec @ARGV'", "5"]
command += ["ping", "www.google.com"]
exec_proc = subprocess.Popen(command)
or you can use the signal.alarm() if you want it with python but it's the same.
Problem
I want to use subprocess to run a program and I need to limit the execution time. For example, I want to kill it if it runs for more than 2 seconds. For common programs, kill() works well. But if I try to run `/usr/bin/time something`, kill() can’t really kill the program. My code below seems doesn’t work well. The program is still running. ``` import subprocess import time exec_proc = subprocess.Popen("/usr/bin/time -f \"%e\\n%M\" ./son > /dev/null", stdout = subprocess.PIPE, stderr = subprocess.STDOUT, shell = True) max_time = 1 cur_time = 0.0 return_code = 0 while cur_time <= max_time: if exec_proc.poll() != None: return_code = exec_proc.poll() break time.sleep(0.1) cur_time += 0.1 if cur_time > max_time: exec_proc.kill() ```