A H
A H

Reputation: 2580

close files opened by batch file on termination

When using task scheduler, if you run a batch program, when ending the script, it only closes the batch file, and not the program spawned by the batch file.

Is there a way to close all programs opened by that batch session when it gets a terminate command?

e.g.

echo started: %date% %time% >> log.txt
calc
timeout 5
echo ended: %date% %time% 
taskkill /im win32calc.exe

Is there a way in batch to run the taskkill command (or another way to close all spawned processes) when it tries to get force closed.

In python, this would be done with a try/finally, like this: try: ... finally: killtask('win32calc') where the finally always runs no matter what.

Or with open 'calc.exe': # run some code

Upvotes: 0

Views: 2463

Answers (1)

Aacini
Aacini

Reputation: 67256

I think the behavior you want can be implemented via a modification of this answer, that is:

rem Start the process that will kill the calc.exe program after 5 seconds
start "WaitingToKill" cmd /C timeout /t 5 ^& taskkill /im calc.exe /f

rem Run the calc.exe program and wait for it to terminate
calc.exe

rem If calc.exe ends before 5 seconds, kill the killer process and terminate
taskkill /fi "WINDOWTITLE eq WaitingToKill" /f

Upvotes: 2

Related Questions