【第22期】观点:IT 行业加班,到底有没有价值?

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]);
                }
            }
        }
    }
版权声明: 举报

相关文章推荐

linux简单易用的看门狗程序

看门狗程序是通过“喂狗”的形式不停的给watchdog写入数据,一旦在一定的时间内没有写入,watchdog就会认为程序发生了崩溃,它能够直接出发芯片复位,让linux系统进行重启。在实际的项目中具有...

Windows下实现应用程序看门狗软件

有时候,我们需要确保一个应用程序长期稳定地运行,但是在Windows平台上由于种种原因,几乎不可能保障一个应用的绝对可靠运行。那么,我们就需要有一个机制,在应用死机﹑异常﹑系统重启等情况下自我恢复,而且能够做一些指定的动作,比如定时重启等。 方案一:把应用注册成服务,并把它放到启动项里。这个方法简...

程序员升职加薪指南!还缺一个“证”!

CSDN出品,立即查看!

嵌入式系统开发

转自:http://blog.csdn.net/loongembedded/article/details/6830148  ********************************Lo...

ARM-Linux驱动移植--Watch Dog Timer(看门狗)驱动移植

硬件平台:FL2440 (S3C2440) 内核版本:2.6.28 软件平台:Ubuntu 11.04 内核版本:2.6.39 交叉编译器:arm-linux-gcc 3.4.1 原创作品,转载请标明出处 1、加载看门狗驱动 insmod wdt.ko wdt.ko为驱动文件名,不加任何参数如果不喂...

汇编写启动代码之关看门狗

本文使用的开发板是九鼎创展的X210 iNand版本。   一、查阅数据手册   <img class="magplus" style="cursor: , pointer;" title="点击查看原始大小图片&q...
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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