I want to using subprocess to run a program, but I need to limit the execution time. For example, if it runs more than 2 seconds, I want to kill it.
For common programs, kill() works well. But if I try to run "/usr/bin/time something", kill() can't really kill the program.
But my code below seems not works well, the program is still running. Please help me, thanks a lot.
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()