Why cannot execute "taskkill" from cmd in c++?

297 Views Asked by At

I want to execute taskkill from cmd in c++ code. I have tried two forms:

  1. Simple form:
system("taskkill /IM 'example.exe' /F");
  1. 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?

1

There are 1 best solutions below

0
wohlstad On BEST ANSWER

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:

  1. Get the process PID from its name (see below).
  2. Open the process using 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++?.

  1. Use the handle with 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).