I want to execute taskkill from cmd in c++ code. I have tried two forms:
- Simple form:
system("taskkill /IM 'example.exe' /F");
- With administrative privilege (because one of my processes has high privilege):
system("runas / profile / user:administrator \"taskkill /IM 'exmaple.exe' /F\"");
Also my c++ program was run as administrator. But none of these commands executed successfully. What is the problem?
An immediate fix could be to remove the single quotes (
') enclosingexample.exe.E.g. instead of:
Use:
Using double quotes (
"- escaped in this case with\) is also OK:However -
As commented above by @PepijnKramer, you can use dedicated windows API functions to do the same. This requires a bit more code, but offers much better control and feedback of errors.
Here's an outline of what you need to do:
OpenProcessAPI to aqcuire a handle to it, withPROCESS_TERMINATEaccess right (see below).An example of getting PID and then a handle to a process by its name: How can I get a process handle by its name in C++?.
TerminateProcessAPI to kill the process. Note that in order to use it:(this should be passed to
OpenProcessvia thedwDesiredAccessparameter).