您的位置:首页 > 编程语言 > C语言/C++

C++实现Windows下的Daemon,监控多个进程

2015-09-07 15:39 295 查看
在windows下,可以用简单的bat实现守护进程的功能,如果dump掉就重新拉起来,百度下就能查到,举个例子:

@echo off

::检测时间间隔,单位:秒
set _interval=5

::需要守护的进程名称
set _processName=print_hello.exe

::需要守护的进程启动命令
set _processCmd=D:\SVN\print_hello.exe
::set _processCmd=print_hello.exe
::需要守护的进程预估启动完毕所需时间,单位:秒
set _processTimeout=1

::进程用户名,一般是Administrator
set _username=adminstrator

:LOOP
set /a isAlive=false
::tasklist /FI "username eq %_username%" | find /C "%_processName%" > temp.txt
tasklist | find /C "%_processName%" > temp.txt
set /p num= < temp.txt
del /F temp.txt

if "%num%" == "0" (
start %_processCmd% | echo start %_processName% at %time%
choice /D y /t %_processTimeout% > nul
)

if "%num%" NEQ "0" echo %_processName% is running
choice /D y /t %_interval% >nul
goto LOOP


这段脚本就可以实现一个Daemon,隔5秒监控print_hello.exe程序一次,保证此程序在系统中的存活,可以用相对路径,也可以用绝对路径;

但用脚本总归有一些限制,比如我这边项目需要监控多个进程,而且是同名的进程,仅能用路径进行区分,对于这类的需求,以上的脚本实现起来相对麻烦,于是自己用C++开发了一个简单的Daemon.exe,通过读取配置文件,可同时监控多个进程,代码如下:

#include <iostream>
#include <windows.h>
#include <process.h>
#include <stdio.h>
#include <tchar.h>
#include <string.h>
using namespace std;

#define MAX_THREAD 5

DWORD WINAPI Daemonproc(LPVOID lpParameter)
{
char *path = (char *)lpParameter;
cout << "child process  " << path<< endl;
STARTUPINFO si;

PROCESS_INFORMATION pi;

ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
do{
if(!CreateProcess( NULL,path,NULL,NULL,FALSE,0,NULL,NULL,&si,&pi))
{
cout << "创建进程失败.." << GetLastError() << endl;
return 0;
}

WaitForSingleObject( pi.hProcess, INFINITE);

cout << "子进程已经退出..." << endl;

CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}while(true);

return 0;
}

int main(int argc, char *argv[])
{
char number[32] = {0};
char **path;
char chpath[128] = {0};
string strpath;
GetModuleFileName(NULL,(LPSTR)chpath,sizeof(chpath));
strpath = chpath;

size_t pos = strpath.rfind("\\");
string strpath2 = strpath.substr(0, pos);
strpath2 +="\\guard.ini";

GetPrivateProfileString("PROCESSNUM", "num", NULL, number, 32, strpath2.c_str());

int pnum = atoi(number);
path = (char **)malloc(pnum * sizeof(char*));
for (int i = 0; i < pnum; i++)
{
path[i] = (char*)malloc(128);
}
char c_tmp[32] = {0};
HANDLE hd[MAX_THREAD];
for (int i = 0; i < pnum; i++)
{
memset(c_tmp, 0, 32);
memset(path[i], 0, 128);
sprintf(c_tmp, "path%d", i+1);
GetPrivateProfileString("PROCESSPATH", c_tmp, NULL, path[i], 128, strpath2.c_str());
hd[i] = CreateThread(NULL,0,Daemonproc,path[i],0,NULL);
if (hd[i] == NULL)
{
ExitProcess(i);
}

}
WaitForMultipleObjects(pnum,hd,TRUE,INFINITE);
for ( int j  = 0; j < pnum; j++)
{
CloseHandle(hd[j]);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: