Reputation: 332
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
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
Reputation: 490038
Fortunately, killing it once you have a PID is pretty easy.
OpenProcess
to get a process handle from the PID
PROCESS_TERMINATE
right.TerminateProcess
to kill the processUpvotes: 3