timeout a process

Tim Golden tjgolden at gmail.com
Sun Jan 15 06:58:47 EST 2006


iapain wrote:
> Hello,
> 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
> infinite loop
>
> 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
extensions.
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):

<code>
import win32process
import win32event

TIMEOUT_SECS = 2

#
# Do as little as possible to get a
# process up and running.
#
hProcess, hThread, pid, tid = \
  win32process.CreateProcess (
    None,
    "c:/winnt/system32/notepad.exe",
    None, None, 0, 0, None, None,
    win32process.STARTUPINFO ()
)
#
# Wait for it to finish, but give up after n secs
#
result = win32event.WaitForSingleObject (
  hProcess,
  1000 * TIMEOUT_SECS
)
#
# If it's timed out, kill it
#
if result == win32event.WAIT_TIMEOUT:
  win32process.TerminateProcess (hProcess, -1)
  print "Killed off"
else:
  print "Died naturally"

</code>

HTH
Tim




More information about the Python-list mailing list