用于监控另一个进程,发现该进程关掉了就自动把它重启。
可以用脚本程序,如vbs或者bat实现。下面程序使用C++实现:用于监视目标程序HTServer.exe,如果目标程序没有在运行,则运行目标程序。
代码如下:
// HTServerMonitor.cpp : Defines the entry point for the console application.
//
#include <iostream>
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
using namespace std;
int _tmain(int argc, _TCHAR *argv[])
{
STARTUPINFO si;
PROCESS_INFORMATION pi; //进程信息:
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
do{
// 创建子进程,判断是否执行成功
if(!CreateProcess( NULL,"cmd /c C:\\Users\\hk\\Desktop\\HTVersions\\HTServer\\HTServerEditVersion4.2\\Debug\\HTServer.exe",NULL,NULL,FALSE,0,NULL,NULL,&si,&pi))
{
cout << "创建进程失败.." << GetLastError() << endl;
system("pause"); //用于测试
return 0;
}
//进程执行成功,打印进程信息
cout << "以下是子进程的信息:" << endl;
cout << "进程ID pi.dwProcessID: " << pi.dwProcessId << endl;
cout << "线程ID pi.dwThreadID : " << pi.dwThreadId << endl;
// 等待知道子进程退出...
WaitForSingleObject( pi.hProcess, INFINITE);//检测进程是否停止
//WaitForSingleObject()函数检查对象的状态,如果是未确定的则等待至超时
//子进程退出
cout << "子进程已经退出..." << endl;
//关闭进程和句柄
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
//system("pause");//执行完毕后等待
}while(true);//如果进程推出就再次执行方法
exit(0);
return 0;
}
以上代码自:http://flylynne.iteye.com/blog/580751
在VC6下编译运行没有问题,但是当用VS08的时候,就会报错:
error C2664:'CreateProcessW' : cannot convert parameter 2 from 'const char[15]' to 'LPWSTR';
解决方法:打开 属性->常规->字符集设置成“未设置”。