C#自制简单进程守护工具

原理分析

在这里插入图片描述

实现过程

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天,革命尚未成功同志还须继续努力!
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值