// ProcessMgr.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "ProcessMgr.h"
#include <process.h>
#include <TlHelp32.h>
using namespace std;
#define g_pProcessMgr ProcessMgr::GetInstance()
#define SAFE_DELETE(xxx) \
CloseHandle(xxx);\
xxx = NULL;
ProcessMgr::ProcessMgr()
{
}
ProcessMgr::~ProcessMgr()
{
}
ProcessMgr* ProcessMgr::GetInstance()
{
if (m_pProcessMgr!=nullptr)
{
m_pProcessMgr = new ProcessMgr();
return m_pProcessMgr;
}
return m_pProcessMgr;
}
bool ProcessMgr::IsProcessExist(DWORD dw_pid)const
{
PROCESSENTRY32 pe;
pe.dwSize = sizeof(PROCESSENTRY32);
HANDLE hSnapshot = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
if(hSnapshot == INVALID_HANDLE_VALUE)
{
cout << "进程不存在" << endl;
CloseHandle(hSnapshot);
return false;
}
BOOL bFindProcess = ::Process32First(hSnapshot,&pe);
if (bFindProcess)
{
do
{
if (pe.th32ProcessID == dw_pid)
{
cout << "进程存在" << endl;
CloseHandle(hSnapshot);
return true;
}
} while (::Process32Next(hSnapshot,&pe));
}
cout << "进程不存在" << endl;
CloseHandle(hSnapshot);
return false;
}
HANDLE ProcessMgr::GetProcessHandle(DWORD dw_pid)const
{
HANDLE hHandle = OpenProcess(PROCESS_ALL_ACCESS ,NULL,dw_pid);
if (hHandle != nullptr)
{
return hHandle;
}
else
{
cout << "获取句柄为空" << endl;
CloseHandle(hHandle);
return nullptr;
}
}
bool ProcessMgr::KillProcess(DWORD dw_pid)const
{
HANDLE hProcess = GetProcessHandle(dw_pid);
if (hProcess!=nullptr)
{
return TerminateProcess(hProcess,IDOK);
}
// 关闭句柄
SAFE_DELETE(hProcess);
return false;
}
bool ProcessMgr::IsProcessRunning(std::wstring str_mutex)
{
HANDLE hMutex = CreateMutex(NULL,FALSE,str_mutex.c_str());
DWORD err_code = GetLastError();
if (hMutex)
{
if (ERROR_ALREADY_EXISTS == err_code)
{
return true; //正在运行
}
::CloseHandle(hMutex);
}
return false;
}
HANDLE ProcessMgr::GetCurrentProcess()
{
return ::GetCurrentProcess();
}
ProcessMgr* ProcessMgr::m_pProcessMgr = nullptr;
int _tmain(int argc, _TCHAR* argv[])
{
g_pProcessMgr->GetProcessHandle(71992);
system("pause");
return 0;
}