0

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?

sh.sagheb
  • 27
  • 1
  • 1
  • 7
  • 4
    Why do you use system? Windows has an API method for that : https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-terminateprocess. – Pepijn Kramer Jan 30 '23 at 08:27
  • Try to remove the single quotes around example.exe: `'example.exe'` -> `example.exe`. – wohlstad Jan 30 '23 at 08:27
  • Have you tried running these commands directly and seeing if they work? – chris Jan 30 '23 at 08:35
  • What I mean is that if you use the API you will be able to get much better error information on why it fails. – Pepijn Kramer Jan 30 '23 at 08:44
  • @wohlstand Thanks, but the result does not changed. – sh.sagheb Jan 30 '23 at 12:03
  • @chris It was successful – sh.sagheb Jan 30 '23 at 12:06
  • @sh.sagheb this is strange. I launched notepad.exe, and tried (in a cmd.exe terminal): `taskkill /IM 'notepad.exe' /F` and got `ERROR: The process "'notepad.exe'" not found.`. Then I tried `taskkill /IM notepad.exe /F` and it succeeded (got: `SUCCESS: The process "notepad.exe" with PID ... has been terminated.`). It also worked when I enclosed notepad.exe with double-quotes (`"`). But not with single quotes (`'`). – wohlstad Jan 30 '23 at 14:48

1 Answers1

1

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).

wohlstad
  • 12,661
  • 10
  • 26
  • 39