c++根据进程名称kill进程(不保险,最好根据进程id)
BOOL ClientApp::KillProcessByName(const TCHAR *lpszProcessName) {
unsigned int pid = -1;
BOOL retval = TRUE;
if (lpszProcessName == NULL)
return -1;
DWORD dwRet = 0;
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 processInfo;
processInfo.dwSize = sizeof(PROCESSENTRY32);
int flag = Process32First(hSnapshot, &processInfo);
// Find the process with name as same as lpszProcessName
while (flag != 0)
{
if (_tcscmp(processInfo.szExeFile, lpszProcessName) == 0) {
// Terminate the process.
pid = processInfo.th32ProcessID;
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
if (TerminateProcess(hProcess, 0) != TRUE) { // Failed to terminate it.
retval = FALSE;
break;
}
}
flag = Process32Next(hSnapshot, &processInfo);
} // while (flag != 0)
CloseHandle(hSnapshot);
if (pid == -1)
return FALSE;
return retval;
}