問題描述:
我們的客戶希望客戶端程序在客戶端上24小時在線,如果因為特殊的原因而崩潰或者退出,應該能自動的重啟程序。
我們所想到的一個解決辦法就是使用一個監控進程,這個進程一開機的時候就會自動嘗試著啟動程序;並且,每隔一段時間就檢查程序是否還啟動著,如果不是的話,則重新啟動程序。
問題分析:
1、首先,是如何在Windows上啟動一個程序,並定時的檢查程序的運行狀態,我們可以用如下的代碼來做這些事情:
[cpp]
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
void _tmain( int argc, TCHAR *argv[] )
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
if( argc != 2 )
{
printf("Usage: %s [cmdline]\n", argv[0]);
return;
}
// Start the child process.
if( !CreateProcess( NULL, // No module name (use command line)
argv[1], // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi ) // Pointer to PROCESS_INFORMATION structure
)
{
printf( "CreateProcess failed (%d).\n", GetLastError() );
return;
}
// Wait until child process exits.
WaitForSingleObject( pi.hProcess, INFINITE );
// Close process and thread handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
}
2、然後需要定期的檢測,並且在子進程退出的時候重新啟動子進程即可。
3、為了確保同一時間只有一個子進程被啟動著,需要確保程序只能啟動一次,我們可以用如下的代碼實現:
[cpp]
#ifndef LimitSingleInstance_H
#define LimitSingleInstance_H
#include <windows.h>
//This code is from Q243953 in case you lose the article and wonder
//where this code came from.
class CLimitSingleInstance
{
protected:
DWORD m_dwLastError;
HANDLE m_hMutex;
public:
CLimitSingleInstance(TCHAR *strMutexName)
{
//Make sure that you use a name that is unique for this application otherwise
//two apps may think they are the same if they are using same name for
//3rd parm to CreateMutex
m_hMutex = CreateMutex(NULL, FALSE, strMutexName); //do early
m_dwLastError = GetLastError(); //save for use later...
}
~CLimitSingleInstance()
{
if (m_hMutex) //Do not forget to close handles.
{
CloseHandle(m_hMutex); //Do as late as possible.
m_hMutex = NULL; //Good habit to be in.
}
}
BOOL IsAnotherInstanceRunning()
{
return (ERROR_ALREADY_EXISTS == m_dwLastError);
}
};
#endif
將上述內容保存為LimitSingleInstance.h,然後在程序的入口處創建其一個實例:
[cpp]
#include "LimitSingleInstance.H"
// The one and only CLimitSingleInstance object.
CLimitSingleInstance g_SingleInstanceObj(TEXT("Global\\{9DA0BEED-7248-450a-B27C-C0409BDC377D}"));
int main(int argc, char* argv[])
{
if (g_SingleInstanceObj.IsAnotherInstanceRunning())
return 0;
//Rest of code.
}
編程環境:
Qt 4.7 + Visual Studio 2008