守护进程的大体思路就是用一个线程函数,一段时间去检测某个进程是否还存在,存在则不管,不存在则重启,或者进程是否属于挂起状态,挂起的话也是重启程序(先kill掉进程,然后重新启动)
1.创建线程
HANDLE hThread1;
DWORD dwThreadId1;
try
{
hThread1 = CreateThread(NULL,0,DoThread,this,0,&dwThreadId1);
}
catch (CMemoryException* e)
{
}
catch (CFileException* e)
{
}
catch (CException* e)
{
}
if (hThread1!=NULL)
{
CloseHandle(hThread1);
}
2.进程检测
HINSTANCE hDll = LoadLibrary(_T("user32.dll"));
CString m_szStatus;
while(1)
{
CWnd* hwnd = CWnd::FindWindow(NULL, TEXT("dataGet"));// m_szName 程序名称
if (NULL != hwnd)
{
if (NULL != hDll)
{
typedef BOOL(WINAPI *PROCISHUNGAPPWINDOW)(HWND);
PROCISHUNGAPPWINDOW IsHungAppWindow = (PROCISHUNGAPPWINDOW)GetProcAddress(hDll, "IsHungAppWindow");
if (IsHungAppWindow(hwnd->GetSafeHwnd()))
{
//先杀掉进程,然后在开启
KillerProcess(TEXT("dataGet.exe"));
m_szStatus =TEXT( "未响应");
RunTheSysProc();
Sleep(1500);
//发送采集消息
CWnd* hwnd_ = CWnd::FindWindow(NULL, TEXT("dataGet"));// m_szName 程序名称
::PostMessage(hwnd_->GetSafeHwnd(),WM_COMMAND, MAKEWPARAM(IDC_BTN_GETD, BN_CLICKED), 0);
}
else
{
m_szStatus = TEXT("正在运行");
}
}
}
else
{
m_szStatus = TEXT("未检测到程序状态!");
RunTheSysProc();
Sleep(1500);
//发送采集消息
CWnd* hwnd_ = CWnd::FindWindow(NULL, TEXT("dataGet"));// m_szName 程序名称
::PostMessage(hwnd_->GetSafeHwnd(),WM_COMMAND, MAKEWPARAM(IDC_BTN_GETD, BN_CLICKED), 0);
}
Sleep(5000);
}
3.启动线程
TCHAR szPath[MAX_PATH];
GetModuleFileName(NULL, szPath, MAX_PATH);
CString strPath = szPath;
strPath = strPath.Left(strPath.ReverseFind('\\')) + TEXT("\\dataGet.exe");
STARTUPINFO StartInfo;
PROCESS_INFORMATION procStruct;
memset(&StartInfo,0,sizeof(STARTUPINFO));
StartInfo.cb = sizeof(STARTUPINFO);
if(!::CreateProcess(
(LPCTSTR) strPath,
NULL,
NULL,
NULL,
FALSE,
NORMAL_PRIORITY_CLASS,
NULL,
NULL,
&StartInfo,
&procStruct))
return false;
return true;
4.kill进程
//创建进程快照(TH32CS_SNAPPROCESS表示创建所有进程的快照)
HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
//PROCESSENTRY32进程快照的结构体
PROCESSENTRY32 pe;
//实例化后使用Process32First获取第一个快照的进程前必做的初始化操作
pe.dwSize = sizeof(PROCESSENTRY32);
//下面的IF效果同:
//if(hProcessSnap == INVALID_HANDLE_VALUE) 无效的句柄
if(!Process32First(hSnapShot,&pe))
{
return FALSE;
}
//将字符串转换为小写
strProcessName.MakeLower();
//如果句柄有效 则一直获取下一个句柄循环下去
while (Process32Next(hSnapShot,&pe))
{
//pe.szExeFile获取当前进程的可执行文件名称
CString scTmp = pe.szExeFile;
//将可执行文件名称所有英文字母修改为小写
scTmp.MakeLower();
//比较当前进程的可执行文件名称和传递进来的文件名称是否相同
//相同的话Compare返回0
if(!scTmp.Compare(strProcessName))
{
//从快照进程中获取该进程的PID(即任务管理器中的PID)
DWORD dwProcessID = pe.th32ProcessID;
HANDLE hProcess = ::OpenProcess(PROCESS_TERMINATE,FALSE,dwProcessID);
::TerminateProcess(hProcess,0);
CloseHandle(hProcess);
return TRUE;
}
scTmp.ReleaseBuffer();
}
strProcessName.ReleaseBuffer();
return FALSE;