I am trying to build and infinite loop handler in python 2.4 on windows
platform. The problem is that i want to create a process and forcely
kill/timeout after 2 sec to handle infinite loop in a gcc complied exe
on cygwin. something like below
os.system("mycpp.exe") # this exe is compiled with g++ and having an
I wish to terminate this after 2 sec. I've tried Watchdog and deamon
thread.. but nothing seem to work here.
I'm not 100% sure, but I think that the following approach will work:
Use the win32process and win32event modules from the pywin32
Use CreateProcess to run your .exe
Use WaitForSingleObject with the process handle and a timeout
Use TerminateProcess to kill your exe
Something like this (tested only casually):
TIMEOUT_SECS = 2
# Do as little as possible to get a
# process up and running.
hProcess, hThread, pid, tid = \
None, None, 0, 0, None, None,
# Wait for it to finish, but give up after n secs
result = win32event.WaitForSingleObject (
1000 * TIMEOUT_SECS
# If it's timed out, kill it
if result == win32event.WAIT_TIMEOUT:
win32process.TerminateProcess (hProcess, -1)
print "Killed off"
print "Died naturally"