1. 程式人生 > >C++看門狗服務程式(程式碼)

C++看門狗服務程式(程式碼)

1、註冊服務

2、檢測指定程序是否執行,如果沒有執行,則執行程序

// WatchDogSvr.cpp : 定義控制檯應用程式的入口點。

//


#include "stdafx.h"
#include "Windows.h" 
#include "tlhelp32.h" 


SERVICE_STATUS m_ServiceStatus; 
SERVICE_STATUS_HANDLE m_ServiceStatusHandle; 
BOOL bRunning=true; 
void WINAPI ServiceMain(DWORD argc, LPTSTR *argv); 
void WINAPI ServiceCtrlHandler(DWORD Opcode); 
BOOL InstallService(); 
BOOL DeleteService(); 
const int nBufSize=512;


void WriteLog(const char* strLog)
{
FILE * fp;
fp=fopen("C:\\WatchDog.log","a");
if( fp==NULL ) return;


//fputs(strLog,fp);
fprintf(fp,"%s\n",strLog);


fclose(fp);
}


int GetProcessCount(const TCHAR* szExeName)
{
TCHAR sztarget[MAX_PATH];
lstrcpy(sztarget, szExeName);
CharLowerBuff(sztarget, MAX_PATH);


int count = 0;
PROCESSENTRY32 my;
HANDLE l = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (((int)l) != -1)
{
my.dwSize = sizeof(my);
if (Process32First(l, &my))
{
do
{
CharLowerBuff(my.szExeFile, MAX_PATH);
if (lstrcmp(sztarget, my.szExeFile) == 0)
{
count++;
}
}while (Process32Next(l, &my));
}
CloseHandle(l);
}


return count;
}


void RunServiceProcess(const TCHAR *strServiceName)
{
//清空結構
STARTUPINFO sInfo;
PROCESS_INFORMATION pInfo;
ZeroMemory(&sInfo,sizeof(sInfo));
sInfo.cb=sizeof(sInfo);
sInfo.dwFlags=STARTF_USESHOWWINDOW;
sInfo.wShowWindow=SW_SHOWNORMAL;


ZeroMemory(&pInfo,sizeof(pInfo));


//輸出出錯資訊
char chBuf[nBufSize];
ZeroMemory(chBuf,nBufSize);


//建立一個程序
if(!::CreateProcess(strServiceName,NULL,
NULL,
NULL,
FALSE,
0,
NULL,
NULL,
&sInfo,
&pInfo))
{
sprintf(chBuf,"CreateProcess failed(%d).\n",GetLastError());
WriteLog(chBuf);


return;
}


// Wait until child process exits.
WaitForSingleObject(pInfo.hProcess,INFINITE);


//關閉程序和執行緒的控制代碼
CloseHandle(pInfo.hProcess);
CloseHandle(pInfo.hThread);
}


void DoTask() 
{
if( GetProcessCount(_T("SjkDataCollect.exe"))==0)
{
RunServiceProcess(_T("C:\\xxx.exe"));
WriteLog("can not find process [SjkDataCollect.exe] and run process!");
}
}


int _tmain(int argc, _TCHAR* argv[])
{


if(argc>1) 

if( wcscmp(argv[1],L"-i")==0) 

if(InstallService()) 
printf("\n Service Installed Sucessfully\n"); 
else 
printf("\n Service has been installed\n"); 

else if(wcscmp(argv[1],L"-d")==0) 

if(DeleteService()) 
printf("\n Service UnInstalled Sucessfully\n"); 
else 
printf("\nInstalled Easin Central Service Not Found\n"); 
}
else 

printf("\nUnknown Switch Usage\nFor Install use Servicetest -i\nFor UnInstall use Servicetest -d\n"); 


else 

SERVICE_TABLE_ENTRY DispatchTable[]={{L"WatchDogSvr",ServiceMain},{NULL,NULL}};   
StartServiceCtrlDispatcher(DispatchTable);  



return 0; 
}




void WINAPI ServiceMain(DWORD argc, LPTSTR *argv) 

//     DWORD status;  
//     DWORD specificError;  
m_ServiceStatus.dwServiceType          = SERVICE_WIN32;  
m_ServiceStatus.dwCurrentState         = SERVICE_START_PENDING;  
m_ServiceStatus.dwControlsAccepted     = SERVICE_ACCEPT_STOP;  
m_ServiceStatus.dwWin32ExitCode        = 0;  
m_ServiceStatus.dwServiceSpecificExitCode = 0;  
m_ServiceStatus.dwCheckPoint           = 0;  
m_ServiceStatus.dwWaitHint             = 0;  


m_ServiceStatusHandle = RegisterServiceCtrlHandler(L"WatchDogSvr",ServiceCtrlHandler);   
if (m_ServiceStatusHandle == (SERVICE_STATUS_HANDLE)0)  
{  
return;  
}      
m_ServiceStatus.dwCurrentState         = SERVICE_RUNNING;  
m_ServiceStatus.dwCheckPoint           = 0;  
m_ServiceStatus.dwWaitHint             = 0;   
if (!SetServiceStatus (m_ServiceStatusHandle,&m_ServiceStatus))  
{  
}  


bRunning=true; 
while(bRunning) 
{    
Sleep(3000); 
//Place Your Code for processing here....   
DoTask(); 

return;  



void WINAPI ServiceCtrlHandler(DWORD Opcode) 

switch(Opcode)  
{  
case SERVICE_CONTROL_PAUSE:  
m_ServiceStatus.dwCurrentState = SERVICE_PAUSED;  
break;  


case SERVICE_CONTROL_CONTINUE:  
m_ServiceStatus.dwCurrentState = SERVICE_RUNNING;  
break;  


case SERVICE_CONTROL_STOP:  
m_ServiceStatus.dwWin32ExitCode = 0;  
m_ServiceStatus.dwCurrentState    = SERVICE_STOPPED;     
m_ServiceStatus.dwCheckPoint      = 0;  
m_ServiceStatus.dwWaitHint        = 0;     
SetServiceStatus (m_ServiceStatusHandle,&m_ServiceStatus); 
bRunning=false; 
break; 


case SERVICE_CONTROL_INTERROGATE:  
break;  
}       
return;  

BOOL InstallService() 

WCHAR strDir[1024]; 
SC_HANDLE schSCManager,schService; 
GetCurrentDirectory(1024,strDir); 
lstrcat(strDir,L"\\WatchDogSvr.exe");  
schSCManager = OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS);   


if (schSCManager == NULL)  
return false; 
LPCTSTR lpszBinaryPathName=strDir; 


schService = CreateService((struct SC_HANDLE__ *)schSCManager,L"WatchDogSvr",L"WatchDogSvr",             // service name to display  
SERVICE_ALL_ACCESS,          // desired access  
SERVICE_INTERACTIVE_PROCESS | SERVICE_WIN32_OWN_PROCESS, // service type  
SERVICE_AUTO_START,        // start type  
SERVICE_ERROR_NORMAL,        // error control type  
lpszBinaryPathName,          // service's binary  
NULL,                        // no load ordering group  
NULL,                        // no tag identifier  
NULL,                        // no dependencies  
NULL,                        // LocalSystem account  
NULL);                       // no password  


if (schService == NULL)  
return false;   
SERVICE_DESCRIPTION   sdBuf; 
sdBuf.lpDescription   =   L"深基坑後臺服務"; 
ChangeServiceConfig2( schService, SERVICE_CONFIG_DESCRIPTION, &sdBuf); 




CloseServiceHandle((struct SC_HANDLE__ *)schService);  
return true; 



BOOL DeleteService() 

HANDLE schSCManager; 
SC_HANDLE hService; 
schSCManager = OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS); 


if (schSCManager == NULL)  
return false;  
hService=OpenService((struct SC_HANDLE__ *)schSCManager,L"WatchDogSvr",SERVICE_ALL_ACCESS); 
if (hService == NULL)  
return false; 
if(DeleteService(hService)==0) 
return false; 
if(CloseServiceHandle(hService)==0) 
return false; 
else 
return true; 
}