C#通过Process和list配合不断检测进程并重启该进程
使用语言:C#
环境:.net Framework 4.6.1 (当前使用) (貌似支持所有环境,我就不多说了)
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace process_monitor { class Program { static List<ProcessInfo> listProcess = new List<ProcessInfo>(); static void Main(string[] args) { CameraInfo camera = new CameraInfo(); CreateProcess(camera); Thread thread = new Thread(Ccout); thread.IsBackground = true; thread.Start(); while (true) { } } /// <summary> /// /// </summary> /// <param name="camera"></param> private static void CreateProcess(CameraInfo camera) { //启动这个进程 var decodeProcess = new Process { StartInfo = new ProcessStartInfo { //Environment.CurrentDirectory 这个是获取本应用程序的路径 FileName = Environment.CurrentDirectory + "\\Jt.exe", //带过去的参数 UseShellExecute = false, RedirectStandardInput = false, RedirectStandardOutput = false, RedirectStandardError = false, CreateNoWindow = true } }; decodeProcess.Start(); //进程信息所在 ProcessInfo processInfo = new ProcessInfo() { processId = decodeProcess.Id, cameraInfo = camera }; //添加进程信息 listProcess.Add(processInfo); } public static void Ccout() { while (true) { Thread.Sleep(5000); try { //获取所有叫jt进程内的信息 Process[] processIdAry = Process.GetProcessesByName("Jt"); //循环我们的信息 foreach (var oneProcess in listProcess) { //如果我们这个ID程序在我们都Pid中出现 if (processIdAry.Where(n => n.Id == oneProcess.processId).Count() > 0) { Console.WriteLine($"{DateTime.Now} 程序运行正常"); } else { Console.WriteLine("一个进程中断,正在执行重启任务"); listProcess.Remove(oneProcess); //获取带过去的参数 CameraInfo camera = oneProcess.cameraInfo; //重启这个进程 CreateProcess(camera); Console.WriteLine("重启成功"); } } } catch (Exception) { } } } } public class CameraInfo { public Guid id { get; set; } public string name { get; set; } } public class ProcessInfo { public int processId { get; set; } public CameraInfo cameraInfo { get; set; } } }一般都是一个服务来的,只是我这样更加容易理解原理,守护服务在百度一搜就能收到,以后我再更新服务的。 标签:CameraInfo,C#,System,process,camera,new,using,控制台,public From: https://www.cnblogs.com/valu/p/17993769