terminateprocess
今天又掉坑里了。用“TerminateProcess”杀某个控制台进程,结果进程杀死了,应用程序还停留在状态栏,任务管理器中的“进程”已找不到被杀死的进程,“应用程序”里还能看到。最后发现是“system("pause");”惹的祸,这个玩意起了一个系统进程。以后慎用。
bool Killprogress(const Dword& _dwId)
{
handle hProcess = ::OpenProcess(PROCESS_TERMINATE, FALSE, _dwId);//通过这个函数判断进程是否活着,不准确
if (nullptr == hProcess)
{
std::cout << "进程的句柄为空!ID = " << _dwId << std::endl;
return false;
}
else
{
dword dwExitCode = _dwId;
::GetExitCodeProcess(hProcess, &dwExitCode);
BOOL bres = ::TerminateProcess(hProcess, dwExitCode);
if (bres == 0)
{
std::cout << "杀死进程出异常:ID = " << _dwId << " 错误码:" << GetLastERROR() << std::endl;
return false;
}
::CloseHandle(hProcess);
}
return true;
}
bool IsExistProgress(const DWORD& _dwId)
{
PROCESSENTRY32 pe;
HANDLE hSnapshot = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);//获取系统进程快照句柄
pe.dwSize = sizeof(PROCESSENTRY32);
if (!::Process32First(hSnapshot, &pe))
{
std::cout << "获取第一个进程句柄失败!" << std::endl;
return false;
}
bool bret = false;
while (true)
{
pe.dwSize = sizeof(PROCESSENTRY32);
if (::Process32Next(hSnapshot, &pe) == FALSE)
break;
if (_dwId == pe.th32ProcessID)
{
bret = true;
break;
}
}
::CloseHandle(hSnapshot);
return bret;
}
相关阅读
WindowsAPI详解——TerminateProcess 终止|杀死其它进
WindowsAPI详解——TerminateProcess 终止|杀死其它进程 - [VC++编程]