C#制作简单的看门狗程序

原创 2016年05月31日 23:45:30

这个类实现了程序退出能重启,但是程序停止运行弹出对话框,进程并没有退出却无法重启。希望有好建议处理这个bug的朋友提出你们的宝贵意见。
源码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.Runtime.InteropServices;

    public  class ProcessWatcher
    {
        /// <summary>
        /// 进程列表
        /// </summary>
        public List<MyProcess> myProcessList;
        private Thread watchThread;
        private int watchWaitingTime = 20;


        /// <summary>
        /// 初始化
        /// -1 process.mj 文件不存在
        /// 0 看护进程不存在
        /// 1 成功
        /// 2 部分进程路径不正确
        /// </summary>
        /// <returns></returns>
        public int init()
        {
            if (!System.IO.File.Exists("process.mj")) return -1;
            string[] processPath = System.IO.File.ReadAllLines("process.mj",Encoding.Default);
            int count = 0;
            myProcessList = new List<MyProcess>();
            foreach (string path in processPath)
            {
                if (System.IO.File.Exists(path))
                {
                    count++;
                    MyProcess mp = new MyProcess(path);
                    myProcessList.Add(mp);
                }  
            }
            if (count == 0) return 0;
            if (count == processPath.Length) return 1;
            return 2;
        }
        /// <summary>
        /// 启动守护
        /// 
        /// </summary>
        /// <param name="sleepTime">等待时间</param>
        /// <returns></returns>
        public int watchStart(int sleepTime)
        {
            watchWaitingTime = sleepTime;
            watchStop();
            watchThread = new Thread(watch);
            watchThread.Start();
            return 0;
        }
        /// <summary>
        /// 关闭守护
        /// </summary>
        /// <returns></returns>
        public int watchStop()
        {
            try
            {
                watchThread.Abort();
            }
            catch
            { }
            return 0;
        }
        /// <summary>
        /// 守护线程,死循环
        /// </summary>
        private void watch()
        {
            while (true)
            {
                if (myProcessList == null) return;
                if (myProcessList.Count < 1) return;
                foreach (MyProcess mp in myProcessList)
                {
                    if (!mp.isAlive())
                    {
                        //Thread.Sleep(1000);
                        //if (!mp.isAlive()) mp.start();
                        mp.start();
                    }
                }
                Thread.Sleep(watchWaitingTime*1000);
            }
        }
        /// <summary>
        /// 全部重启,如果已经启动则先关闭
        /// </summary>
        public void startAll()
        {
            if (myProcessList == null) return;
            if (myProcessList.Count < 1) return;
            foreach (MyProcess mp in myProcessList)
            {
                if (!mp.isAlive()) mp.start();
            }
        }
        /// <summary>
        /// 关闭所有守护进程
        /// </summary>
        public void stopAll()
        {
            if (myProcessList == null) return;
            if (myProcessList.Count < 1) return;
            foreach (MyProcess mp in myProcessList)
            {
                 mp.stop();
            }
        }
        /// <summary>
        /// 进程状态
        /// 1 显示界面
        /// 2 影藏界面
        /// 3 重启
        /// 4 停止
       /// </summary>
       /// <param name="state"></param>
       /// <param name="name"></param>
        public void setProcessState(int state,string name)
        {
            foreach (ProcessWatcher.MyProcess p in myProcessList)
            {
                if (p.Name == name)
                {
                    switch (state)
                    {
                        case 1:
                            p.show();
                            break;
                        case 2:
                            p.hide();
                            break;
                        case 3:
                            p.start();
                            break;
                        case 4:
                            p.stop();
                            break; 
                    }
                    break;
                }
            }
        }
        /// <summary>
        /// 判断某个线程是否存在
        /// </summary>
        /// <param name="name">线程名字</param>
        /// <returns></returns>
        public Boolean processIsAlive(string name)
        {
            if (myProcessList == null) return false;
            if (myProcessList.Count < 1) return false;
            foreach (MyProcess mp in myProcessList)
            {
                if (mp.Name == name)
                {
                    return mp.isAlive();
                }
            }
            return false;
        }

        /// <summary>
        /// 显示窗体
        /// </summary>
        /// <param name="hWnd">窗体句柄</param>
        /// <param name="nCmdShow">0 隐藏,1显示</param>
        /// <returns></returns>
        [DllImport("user32.dll", EntryPoint = "ShowWindow", SetLastError = true)]
        static extern bool ShowWindow(IntPtr hWnd, uint nCmdShow);
        public class MyProcess
        {

            private  string name;
            private  string path;
            private IntPtr ptrHide;
            //private Process process;
            public MyProcess(string path)
            {
                string[] s = path.Split('\\');
                this.name = s[s.Length-1];
                this.name = name.Substring(0,name.Length-4);
                this.path = path;
                ptrHide = IntPtr.Zero;
            }
            /// <summary>
            /// 进程名字
            /// </summary>
            public string Name
            {
                get { return name; }
            }
            /// <summary>
            /// 进程路径
            /// </summary>
            public string Path
            {
                get { return path; }
            }
            /// <summary>
            /// 进程状态
            /// </summary>
            /// <returns></returns>
            public Boolean isAlive()
            {
                Process p = process();
                if (p == null) return false;
                if (p.Responding == true) return true;
                return !p.HasExited;
                //try
                //{
                //    return process().Responding;
                //}
                //catch
                //{
                //    return false;
                //}
            }
            /// <summary>
            /// 启动,如果已经启动,则关闭后再启动
            /// </summary>
            public void start()
            {
                stop();
                Thread.Sleep(500);
                Process.Start(path);
                writeLog("启动程序"+name);
            }
            /// <summary>
            /// 关闭
            /// </summary>
            public void stop()
            {
                try
                {
                    process().Kill();
                    writeLog("关闭程序" + name);
                }
                catch
                { }
            }
            /// <summary>
            /// 显示
            /// </summary>
            public void show()
            {
                if (process() != null)
                {
                    if (ptrHide == IntPtr.Zero)
                    {
                        ShowWindow(process().MainWindowHandle, 1);
                    }
                    else
                    {
                        ShowWindow(ptrHide, 1);
                        ptrHide = IntPtr.Zero;
                    }
                }
            }
            /// <summary>
            /// 隐藏
            /// </summary>
            public void hide()
            {
                if (process() != null)
                {
                    if (ptrHide != IntPtr.Zero) return;  //防止多次隐藏。
                    ptrHide = process().MainWindowHandle;//隐藏前保存窗体句柄,隐藏后从新获取的句柄与此不同。
                    ShowWindow(ptrHide, 0);
                }
            }
            /// <summary>
            /// 获取进程
            /// </summary>
            /// <returns></returns>
            private Process process()
            {
                Process[] proc = Process.GetProcessesByName(name);
                if (proc.Length > 0)
                {
                    return proc[0];
                }
                return null;
            }
            /// <summary>
            ///
            /// </summary>
            readonly static ReaderWriterLockSlim _rw = new ReaderWriterLockSlim();
            /// <summary>
            /// 写日志文件
            /// </summary>
            /// <param name="str_msg"></param>
            public static void writeLog(string str_msg)
            {
                if (System.IO.Directory.Exists("logW") == false) System.IO.Directory.CreateDirectory("logW");
                string msg = DateTime.Now.ToLongDateString() + DateTime.Now.ToLongTimeString() + ":" + str_msg + "\r\n";
                _rw.EnterWriteLock();
                System.IO.File.AppendAllText("logW\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt", msg);
                _rw.ExitWriteLock();
                string[] s = System.IO.Directory.GetFiles("logW");
                if (s.Length > 7)
                {
                    System.IO.File.Delete(s[0]);
                }
            }
        }
    }
版权声明:

相关文章推荐

简单的WATCHDOG定时器(看门狗)

#include #include #include #include #include #include #include #include #include #include #define WA...

基于STR711的看门狗程序

  • 2008-08-01 08:08
  • 157KB
  • 下载

window 看门狗程序

  • 2013-09-16 10:07
  • 2.06MB
  • 下载

STC89系列单片机看门狗的使用及应用程序

转载:STC89系列单片机看门狗的使用及应用程序    “看门狗”概念及其应用在由单片机构成的系统中,由于单片机的工作有可能会受到来自外界电磁场的干扰,造成程序的跑飞,从而陷入死循环...

看门狗程序

裸奔程序之看门狗定时器

WATCHDOG定时器简介:         WATCHDOG定时器也可以像一般的16位定时器一样用于产生周期性中断,也可以用于发出复位信号以重启时常的系统。它的结构与PWM很相似,如下图所示: ...

第一个驱动程序:at91sam9g45核心板的看门狗驱动

纪念第一个驱动程序:at91sam9g45核心板的看门狗驱动看门狗的驱动一般来说比较简单,只要做寄存器的设置实现开启、关闭、喂狗功能。本项目中我们使用的是at91sam9g45处理器,带有看门狗定时器...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)