Process Daemons

Posted by jc_ply on Thu, 09 Apr 2020 17:50:08 +0200

Process Daemons

1. Write in front

Often write some service programs, sometimes to monitor the running state of the service program, so we made a process daemonic tool.

2. analysis

Get the list of specified processes through Process.GetProcessesByName(ProcessName).

Use Process.MainModule.FileName to determine whether the program is running.

3. Program implementation

The main code to implement the program will be pasted below.

        /// <summary>
        /// To determine whether the process is running, you can use the full path of the program
        /// </summary>
        /// <param name="ProcessName">Process name</param>
        /// <param name="FileName">Process full path</param>
        public static bool GetProcess(string ProcessName, string FileName = null)
        {
            Process[] ps = Process.GetProcessesByName(ProcessName);
            foreach (Process p in ps)
            {
                if (string.IsNullOrEmpty(FileName))//No value
                {
                    return true;
                }
                else//Appoint
                {
                    if (string.Equals(p.MainModule.FileName, FileName, StringComparison.CurrentCultureIgnoreCase))
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// Startup program
        /// </summary>
        /// <param name="FileName">Program path</param>
        public static bool RestartProcess(string FileName)
        {
            try
            {
                Process.Start(FileName);
                return true;
            }
            catch (Exception ex)
            {
                Log4Net.LogInfo(string.Format("Startup program exception:{0}", ex.Message));
                return false;
            }
        }

4. Program interface

5. function

1. Set up the program monitoring list.
2. It supports the monitoring of different running paths of the same program.
3. Interface log and file log.

Download address: https://pan.baidu.com/s/1y1ApRjcLoDdKssXsVOQfCQ extraction code: gder

Topics: C#