I'm writing Python 2.7
that need to run sub-process and terminate it if the subprocess user time exceeded max time.
The definiton for user time can be found in this answer to What do 'real', 'user' and 'sys' mean in the output of time(1)?
So far I have this:
Code
from multiprocessing import Process
import time
def do_something():
pass
def run_process_limited_time(max_seconds):
# init Process
p = Process(target=do_something, args=())
# start process
p.start()
run_time = 0;
sleep_time = 1;
while 1:
# sleep for sleep_time seconds
time.sleep(sleep_time)
# increase run time
run_time += sleep_time
# if process is not alive, we can break the loop
if not p.is_alive():
break
# if process is still alive after max_seconds, kill it!
# TBD - condition is not sufficient
elif run_time > max_seconds:
p.terminate()
break
def main():
run_process_limited_time(10)
if __name__ == "__main__":
main()
Question
the condition elif run_time > max_seconds
is not good enough. I'd like to check that max seconds does not exceed user time only. Not sure I can do it using Process
module but I'm open to new ideas.