原理分析
实现过程
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace onenetjson
{
class Program
{
static void Main(string[] args)
{
Thread protect = new Thread(new ThreadStart(Protect));//实例化循环线程
protect.Start();//启动线程
}
[DllImport("shell32.dll")]
public static extern int ShellExecute(IntPtr hwnd, StringBuilder lpszOp, StringBuilder lpszFile, StringBuilder lpszParams, StringBuilder lpszDir, int FsShowCmd);
public static void Protect()
{
while (true)
{
Process[] ps = Process.GetProcessesByName("目标程序进程名");
bool run = false;
if (ps.Length > 0)
{
foreach (Process p in ps)
{
run = true;
break;
}
}
if (run)
{
Console.WriteLine("已检测到目标程序正在运行");
}
else
{
WriteLog writeLog = new WriteLog();
writeLog.ShowLog("目标程序出现异常--");
Console.WriteLine("目标程序出现异常");
ShellExecute(IntPtr.Zero, new StringBuilder("Open"), new StringBuilder("目标程序文件名"), new StringBuilder(""), new StringBuilder(@".\"), 1);
}
Thread.Sleep(3000);
}
}
}
}
异常记录class
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace onenetjson
{
class WriteLog
{
public void ShowLog(string log)
{
File.AppendAllText("log.txt", "\r\n" + log + GetNowDate());
}
private string GetNowDate()//读取本地日期时间
{
string t = DateTime.Now.ToString();
return t;
}
}
}
总结
本次写的进程守护简单可靠,去掉很多市面上那些华而不实的功能。
这是我学C#第147天,革命尚未成功同志还须继续努力!