How to use c# to implement universal daemon

Time:2021-7-26

1. Download

Source code download: http://files.cnblogs.com/tianzhiliang/CocoWatcher.rar

Installation package download: http://files.cnblogs.com/tianzhiliang/CocoWatcher_ Setup.rar

Local download: http://xiazai.jb51.net/201910/yuanma/CocoWatcher (jb51net).rar

2. Installation precautions

Configure the applications you want to guard in the configuration file. The applications are separated by commas:


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 <appSettings>
 <add key="ProcessAddress" value="
 d:\war3.exe,
 d:\note.txt,
 d:\girl.jpg
 " />
 </appSettings>
</configuration>

This project is a Windows service. If you directly open “cocowatcher. Exe”, an error will be reported, as shown in Figure 1:

To run the daemon, you need to install windows services. Click the batch document “install. Bat”. The details of “install. Bat” are as follows:


"%cd%\InstallUtil.exe" "%cd%\CocoWatcher.exe"
net start "CocoWatcher"
pause

If you want to uninstall the daemon, click the batch document “uninstall. Bat” and the specific contents of “uninstall. Bat” are as follows:


net stop "CocoWatcher"
"%cd%\InstallUtil.exe" "%cd%\CocoWatcher.exe" -u
taskkill /f /im CocoWatcher.exe
pause

3. Demand analysis

The user specifies an unlimited number of applications to guard. The application includes not only exe executable files, but also all applications that can be opened and executed by double clicking, such as JPG and TXT. After the user sets the application to be guarded, close the application (including legal and illegal shutdown), and the application shall be able to restart and open immediately. When the computer restarts, all the applications to be guarded can be opened automatically.

4. Detailed design

To realize the above requirements, first provide a configuration file so that users can freely configure the applications to be guarded. So, what information does the configuration file need to configure the application? Answer: the full path of the application.

OK, we already know the full path of the application to be guarded. How to complete the guardian task next? First, compare the paths of the daemons that have been opened with those of the daemons that have been opened. Then, if the daemons that have been opened by the daemons and the daemons that have been opened by the daemons, we will check the paths that have been opened by the daemons, and if the daemons that have been opened by the daemons are the same as those of the daemons that have been opened by the daemons, Indicates that the process has been closed. At this time, release the process handle memory and restart the process. If all processes in the task management process list are traversed and no process consistent with the full path of the application to be guarded is found, it indicates that the application to be guarded has not been opened. At this time, start the application and then turn to the monitoring process.

It is worth noting that additional threads must be allocated to monitor the application to be guarded. Why? Because if you use the main thread (entry function thread) to perform monitoring tasks, it will be blocked for a long time and will not be activated until the process exits, so you can’t run subsequent programs. Moreover, the monitor program needs to use an endless loop to realize continuous monitoring. If the main thread enters an endless loop, it will not be able to monitor other processes to be guarded.

5. Code explanation

For the development steps of windows services, please refer to MSDN, which is omitted here. The key codes are posted below for explanation.

Read the “processaddress” node in the configuration file, obtain the full directory of the application to be guarded, verify the full directory of the application, and enter the process of scanning the task manager process list if it is legal.

/// <summary>
///Start monitoring
/// </summary>
private void StartWatch()
{
 if (this._processAddress != null)
 {
 if (this._processAddress.Length > 0)
 {
 foreach (string str in _processAddress)
 {
 if (str.Trim() != "")
 {
  if (File.Exists(str.Trim()))
  {
  this.ScanProcessList(str.Trim());
  }
 }
 }
 }
 }
}

Open the task manager, check which processes are running, and then read out the full path of these processes one by one. Compare it with the full path of the application to be guarded. If it is consistent, it indicates that the application to be guarded has been opened and enters the monitoring process. If all processes in the task management process list are traversed and no process consistent with the full path of the application to be guarded is found, it indicates that the application to be guarded has not been opened. At this time, start the application and then turn to the monitoring process.

/// <summary>
///Scan the process list to determine whether the full path corresponding to the process is consistent with the specified path
///If so, the process has started
///If not, the process has not been started
/// </summary>
/// <param name="strAddress"></param>
private void ScanProcessList(string address)
{
 Process[] arrayProcess = Process.GetProcesses();
 foreach (Process p in arrayProcess)
 {
 //System and idle processes will deny access to their full path
 if (p.ProcessName != "System" && p.ProcessName != "Idle")
 {
 try
 {
 if (this.FormatPath(address) == this.FormatPath(p.MainModule.FileName.ToString()))
 {
  //Process started
  this.WatchProcess(p, address);
  return;
 }
 }
 catch
 {
 //Access to the full path of the process is denied
 This. Savelog ("process (" + p.id.tostring() + ") (" + p.processname. Tostring() + ") denied access to the full path!");
 }
 }
 }
 
 //The process has not started
 Process process = new Process();
 process.StartInfo.FileName = address;
 process.Start();
 this.WatchProcess(process, address);
}

Assign a thread to perform monitoring tasks:

/// <summary>
 ///Listening process
 /// </summary>
 /// <param name="p"></param>
 /// <param name="address"></param>
 private void WatchProcess(Process process, string address)
 {
 ProcessRestart objProcessRestart = new ProcessRestart(process, address);
 Thread thread = new Thread(new ThreadStart(objProcessRestart.RestartProcess));
 thread.Start();
 }
 
 
public class ProcessRestart
{
 //Field
 private Process _process;
 private string _address;
 
 
 /// <summary>
 ///Constructor
 /// </summary>
 public ProcessRestart()
 {}
 
 
 /// <summary>
 ///Constructor
 /// </summary>
 /// <param name="process"></param>
 /// <param name="address"></param>
 public ProcessRestart(Process process, string address)
 {
 this._process = process;
 this._address = address;
 }
 
 
 /// <summary>
 ///Restart process
 /// </summary>
 public void RestartProcess()
 {
 try
 {
 while (true)
 {
 this._process.WaitForExit();
 this._ process.Close(); // Release handle of exited process
 this._process.StartInfo.FileName = this._address;
 this._process.Start();
 
 Thread.Sleep(1000);
 }
 }
 catch (Exception ex)
 {
 ProcessWatcher objProcessWatcher = new ProcessWatcher();
 Objprocesswatcher. Savelog ("restartprocess() error, monitor has cancelled the process()"
 + this._process.Id.ToString() +")(" + this._process.ProcessName.ToString() 
 +"), the error description is:" + ex.message. Tostring());
 }
 }
}

summary

The above is the whole content of this article. I hope the content of this article has certain reference and learning value for your study or work. Thank you for your support for developpaer.

Recommended Today

Programming Xiaobai must understand the network principle

How is the network composed? Why can we easily surf the Internet now?Whether you are a computer major or not, you may always have such questions in your heart!And today we will solve this matter and tell you the real answer! Basic composition of network First, let’s look at this sentence Connect all computers together […]