I want to execute taskkill
from cmd in c++ code. I have tried two forms:
system("taskkill /IM 'example.exe' /F");
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 ('
) enclosing example.exe
.
E.g. instead of:
system("taskkill /IM 'example.exe' /F");
Use:
system("taskkill /IM example.exe /F");
Using double quotes ("
- escaped in this case with \
) is also OK:
system("taskkill /IM \"example.exe\" /F");
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:
OpenProcess
API to aqcuire a handle to it, with PROCESS_TERMINATE
access 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++?.
TerminateProcess
API to kill the process.
Note that in order to use it:The handle must have the PROCESS_TERMINATE access right.
(this should be passed to OpenProcess
via the dwDesiredAccess
parameter).