Kill batch file in such a way that its children ar

2019-06-27 04:49发布

问题:

I need to start an exe from a cmd (wrap the exe so I can supply some command-line options). The problem is that just calling the exe from the cmd does not make the wrapping completely transparent: if the .exe hangs, killing the cmd won't kill the exe. I need it to kill the exe too. Can I do that in plain Windows (from XP up), without adding any dependencies?

In Bash you have exec which replaces the shell process with the supplied command. This is handy for writing wrapper scripts, making the wrapping process completely transparent. I know Windows lacks execve() to make this possible, but I'm only interested in the parent-killing-its-children part.

CLARIFICATION: I'm not looking for ways to kill the exe, I am looking for ways to wrap (start) the exe so that killing it using standard ways (eg. Ctrl+C or from task manager) works. For instance, I could create a lnk file (Windows shortcut) and get this behavior, but I want to do it from a script (for one, lnks only work with absolute paths, I can't deploy that).

Thanks.

回答1:

Taskkill can be used to match certain criteria. By entering Taskkill/? you get the manual and can read up on how to filter using common properties. I assume that all your children share a common portion in their name. You could use taskkill to math the name with wildcards and close all children that matched that name.


EDIT (taken from the comments section): As IInspectable points out you can kill all child processes using the /T flag.


EDIT starting from a batch you could use START (reference here) to launch the exe parallel to the batch and have your abort in the batch.

Edit i wrote and tested this mini example:

@echo off
echo starting %1
start %1
echo Any key to kill execution
pause >>  NUL
taskkill /IM %1 /t