2

I have a batch file that calls an external program that periodically hangs. What I would like to do is set a time limit on the batch file / CMD prompt such that it automatically closes after a certain period of time. One catch is that the external program that hangs may have one or more instances running at a given time, and I only want the batch file hitting its time limit to close the instance of the program triggered by the batch. How can I accomplish this? Ideally a solution would work on Windows XP, Vista, and 7.

2 Answers 2

1
REM start the program as quickly as possible to avoid other processes starting
tasklist > file1.txt & start notepad.exe & tasklist > file2.txt
REM Find the PID of the program we just started
for /f "tokens=2" %%a in ('fc file1.txt file2.txt^|find "notepad.exe"') do set PID=%%a
REM delay for 5 seconds
FOR /l %%a in (5,-1,1) do (Echo closing in %%as&ping -n 2 -w 1 127.0.0.1>NUL)
REM delete the program using it's PID
tskill %PID%

the ping -n 2 -w 1 127.0.0.1 will pause for almost exactly 1 second (the amount of time between 2 pings)
This works on XP, as choice is not included in XP

-1

Write this batch:

@echo off    
choice /t <waiting time in seconds> /d y
taskkill /im <process name> /f /fi "status eq not responding"

Put this in a loop if required.

4
  • 1
    This does not discriminate for the instance started by the batch file. And status not responding might only work for GUI programs.
    – Joey
    Jun 27, 2012 at 11:36
  • touché about the instance.. the status would work for everything..it is basically status you see in task manager....if that status is "running" and still program hangs, i doubt there is any way to detect the hang... Jun 27, 2012 at 11:41
  • Well, the not responding one would be detected by the window manager when a program cannot process events in its message queue. But that requires a window and I've never seen console programs "hang" in that fashion. Presumably because the console host process never hangs and the program running inside never talks with the WM directly.
    – Joey
    Jun 27, 2012 at 11:45
  • In this case the process is still "running" per the task manager, but it has suffered a network timeout and it just sitting there waiting for the user to see and deal with it. In this case, as I don't want the user to see/deal with that, I'm okay with just indiscriminately killing the process every few hours (it recovers gracefully enough). As Joey pointed out, it will kill all of the processes with the same name rather than the one I just started. I see that taskkill has an option to kill by PID, but I don't know how to get the PID of an instance when I launch it. Jun 27, 2012 at 17:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .