lll
lll

Reputation: 332

Way to kill a process programmatically by PID

Working Environment: c++, windows

I want to store all pids (not process name), then kill processes programatically when I want to kill. I know I can kill a process by using system("taskkill /pid xxxx"), but I want to know better/best way to kill a process by pid. What is the best way to kill a process and why?

Upvotes: 3

Views: 3843

Answers (2)

Maxime
Maxime

Reputation: 868

You can kill the process using OpenProcess() and TerminateProcess(). The code will look something like this :

HANDLE handle = OpenProcess(PROCESS_TERMINATE, FALSE, ProcessID);
if (NULL != handle) {   
    TerminateProcess(handle, 0);
    CloseHandle(handle);
}

For the inconvenience of the use of system("taskkill /pid xxxx"), I invite you to read this post. A large number of answers have been given to explain why not to use this expression.

  • Slow: It has to jump through lots of unnecessary Windows code and a separate program for a simple operation.

  • Not portable: Dependent on the pause program.

  • Not good style: Making a System call should only be done when really necessary

Upvotes: 2

Jerry Coffin
Jerry Coffin

Reputation: 490038

Fortunately, killing it once you have a PID is pretty easy.

  1. do OpenProcess to get a process handle from the PID
    • be sure to specify the PROCESS_TERMINATE right.
  2. do TerminateProcess to kill the process

Upvotes: 3

Related Questions