为了监控程序异常关闭,开发了守护进程。监控进程,如果进程关闭,自动启动进程。保证进程持续运行。
守护进程使用Topshelf类库做成Windows服务,在系统后台运行。
守护进程及代码下载:
c#实现的守护进程,包含代码资源-CSDN文库https://download.csdn.net/download/xuhang01/88657503
使用方法:
1 首先在配置文件配置需监控进程,可以同时监控多个进程。
<?xml version="1.0" encoding="utf-8" ?>
<ArrayOfProgramInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ProgramInfo>
<!-- 程序进程名 -->
<ProcessName>程序1</ProcessName>
<ProgramName>程序1.exe</ProgramName>
<Path>D:\程序1</Path>
<!-- 检测间隔,每个20秒检测该程序是否启动,如未启动,守护进程将启动该程序 -->
<Interval>20</Interval>
</ProgramInfo>
<ProgramInfo>
<!-- 程序进程名 -->
<ProcessName>程序2</ProcessName>
<ProgramName>程序2.exe</ProgramName>
<Path>D:\程序2</Path>
<!-- 检测间隔,每个20秒检测该程序是否启动,如未启动,守护进程将启动该程序 -->
<Interval>20</Interval>
</ProgramInfo>
</ArrayOfProgramInfo>
2 安装守护进程
使用命令行安装,如下所示:
@echo off
if not "%OS%"=="Windows_NT" exit
title WindosActive
cd /D %~dp0
rem 安装服务
WinHook.exe install
rem启动
WinHook.exe start
rem 卸载
WinHook.exe uninstall
主要代码如下:
public class ProgramMonitor
{
Log _log = new Log(LogType.Monthly);
[DllImport("kernel32.dll")]
public static extern int WinExec(string CmdLine, int ShowCmd);
public void Start()
{
List<ProgramInfo> programList = null;
//通过配置文件反序列化监控程序实体类
string xmlPath = System.AppDomain.CurrentDomain.BaseDirectory + "ProgramList.xml";
using (FileStream stream = new FileStream(xmlPath, FileMode.Open))
{
XmlSerializer xml = new XmlSerializer(typeof(List<ProgramInfo>));
programList = (List<ProgramInfo>)xml.Deserialize(stream);
}
Task.Run(() =>
{
foreach(var g in programList)
{
System.Timers.Timer t = new System.Timers.Timer(g.Interval * 1000);
t.Elapsed += (sender, e) =>
{
if (!checkSelfExeExist(g.ProcessName))
{
ProcessStartInfo info = new ProcessStartInfo();
info.WorkingDirectory = g.Path;
info.UseShellExecute = true;
info.FileName = g.ProgramName;
info.WindowStyle = ProcessWindowStyle.Normal;
info.CreateNoWindow = false;
_log.Write("程序" + g.ProgramName + "已关闭");
string cmd = g.Path+"\\"+g.ProgramName;
try
{
Process pro = Process.Start(info);
pro.WaitForExit();
}catch(Exception ex)
{
_log.Write("启动程序" + g.ProgramName + "失败,"+ex.Message);
}
}
};
t.Start();
}
});
}
public void Stop()
{
Task.Run(() =>
{
_log.Write("服务停止。。。");
});
}
//检测自身程序是否存在
private bool checkSelfExeExist(string strExe)
{
int count = 0;
Process[] vProcesses = Process.GetProcesses();
foreach (Process vProcess in vProcesses)
{
if (vProcess.ProcessName.Equals(strExe))
{
count++;
}
}
return count >= 1;
}
}