my python code goes like this:
def a():
...
...
subprocess.call()
...
...
def b():
...
...
and so on.
My task:
1) If subprocess.call()
returns within 3 seconds, my execution should continue the moment subprocess.call()
returns.
2) If subprocess.call()
does not return within 3 seconds, the subprocess.call()
should be terminated and my execution should continue after 3 seconds.
3) Until subprocess.call()
returns or 3 seconds finishes, the further execution should not take place.
This can be done with threads but how?
Relevant part of the real code goes like this:
...
cmd = ["gcc", "-O2", srcname, "-o", execname];
p = subprocess.Popen(cmd,stderr=errfile)//compiling C program
...
...
inputfile=open(input,'w')
inputfile.write(scanf_elements)
inputfile.close()
inputfile=open(input,'r')
tempfile=open(temp,'w')
subprocess.call(["./"+execname,str(commandline_argument)],stdin=inputfile,stdout=tempfile); //executing C program
tempfile.close()
inputfile.close()
...
...
I am trying to compile and execute a C program using python. When I am executing C program using subprocess.call() and suppose if the C program contains an infinite loop, then the subprocess.call() should be terminated after 3 seconds and the program should continue. I should be able to know whether the subprocess.call() was forcefully terminated or successfully executed so that I can accordingly print the message in the following code.
The back end gcc is of linux.
I have written the above code which is working and satisfying all my contstraints. The link https://docs.python.org/2/library/thread.html says:
thread.exit() Raise the SystemExit exception. When not caught, this will cause the thread to exit silently.
So I suppose there should be no problem of orphan processes, blocked resources, etc. Please suggest.
Finally the below code worked:
On *nix, you could use
signal.alarm()
-based solution:Here's a portable
threading.Timer()
-based solution:If you're willing to convert your call to a
Popen
constructor instead ofcall
(same way you are runninggcc
), then one way to approach this is to wait 3 seconds, poll the subprocess, and then take action based on whether itsreturncode
attribute is stillNone
or not. Consider the following highly contrived example:And this results in different logging output depending upon whether the child process completed within 3 seconds or not:
Note that this approach above will always wait 3 seconds even if the subprocess completes sooner than that. You could convert the above into something like a loop that continually polls the child process if you want different behavior - you'll just need to keep track of how much time has elapsed.