Implementing a generic daemon in C #

Source: Internet
Author: User

1. Download

SOURCE Download: http://pan.baidu.com/s/1vqDA2

installation package Download: http://pan.baidu.com/s/1sjmEB0p

2. Precautions for installation

    • Configure the application you want to protect in configuration files, separated by commas between applications
<?xml version="1.0" encoding="utf-8" ?>< configuration>  <appSettings>    <add key="processaddress" value= "          D:\war3.exe,         d:\note.exe,         d:\girl.jpg    "  />  </ Appsettings></configuration>

The project is a Windows service, directly open "CocoWatcher.exe" will error, 1 shows:

Run the "Installutil.exe" file at this time, then run the daemon to install the Windows service, click on the batch document "install. bat" and then go to "Administrative Tools"-"services" to see that the Cocowatcher service has been started. The process in the configuration file is protected at this time. At this point, go to the task Manager to close the process in the configuration file can be found, has not been closed.

The "Install. Bat" Specific content is as follows:

" %cd%\installutil.exe " " %cd%\cocowatcher.exe "  "cocowatcher"pause

If you do not want to protect the process, you need to uninstall the daemon, click on the batch document "uninstall. bat", "Uninstall. Bat" File details are as follows:

" Cocowatcher " " %cd%\installutil.exe " " %cd%\cocowatcher.exe "  -/F/im Cocowatcher.exepause

3. Demand Analysis

The user specifies an unlimited number of applications to be guarded, including not only EXE executables, but also all applications that can double-click open execution, such as JPG and txt. After the user has set up the application to be guarded, close the application (including legal and illegal shutdown) and the application should be able to restart immediately. When the computer restarts, the application to be guarded can also be opened automatically.

4. Detailed design

To achieve these requirements, first provide a profile that allows users to freely configure the application to be guarded. So, what information does the profile configure for the application? Answer: The full path of the application.

OK, now that we know the full path of the application to be guarded, how do we complete the daemon task? First, we should open the Task Manager, look at what processes are running, and then read out the full path of these processes, and the full path alignment of the application to be guarded, if it is consistent, the application to be guarded is turned on, at this point to assign a thread to monitor the process handle, when the process handle returns information, Indicates that the process has been closed, freeing the process handle memory and restarting the process. If you traverse all the processes in the task management process list and do not find a process that is consistent with the full path of the application to be guarded, the application to be guarded is not already open, and the application is started and then transferred to the monitoring process.

It is important to note that additional threads must be allocated to monitor the application to be guarded, why? Because if you use the main thread (the entry function thread) to perform the monitoring task, it will be blocked for a long time until the process exits to be activated so that subsequent programs cannot be run. Moreover, the monitoring program to achieve continuous monitoring, to use the dead loop, if the main thread into the dead loop, you can not monitor the other to protect the process.

5. Detailed Code

For the development steps of Windows services, please refer to MSDN, omitted here. The key code is posted below to explain.

Read the "processaddress" node in the configuration file, get the full directory of the application to be guarded, verify the full directory of the application, and, if it is legitimate, go to the Scan Task Manager process list process.

/// <summary>///Start Monitoring/// </summary>Private voidStartwatch () {if( This. _processaddress! =NULL)    {        if( This. _processaddress.length >0)        {            foreach(stringStrinch_processaddress) {                if(str. Trim ()! ="")                {                    if(File.exists (str. Trim ())) { This. Scanprocesslist (str.                    Trim ()); }                }            }        }    }}

Open Task Manager to see what processes are running, and then read out the full path of those processes, with the full path alignment of the application to be guarded, and, if so, the application to be guarded is turned on and into the monitoring process. If you traverse all the processes in the task management process list and do not find a process that is consistent with the full path of the application to be guarded, the application to be guarded is not already open, and the application is started and then transferred to the monitoring process.

/// <summary>///scan the list of processes to determine if the full path corresponds to the specified path///if consistent, indicates that the process has started///if it is not consistent, the process has not started/// </summary>/// <param name= "straddress" ></param>Private voidScanprocesslist (stringaddress) {process[] arrayprocess=process.getprocesses (); foreach(Process Pincharrayprocess) {        //system, Idle process denies access to its full path        if(P.processname! ="System"&& P.processname! ="Idle")        {            Try            {                if( This. Formatpath (address) = = This. Formatpath (P.mainmodule.filename.tostring ())) {//process has started                     This.                    Watchprocess (P, address); return; }            }            Catch            {                //deny access to the full path of the process                 This. Savelog ("Process ("+ p.id.tostring () +")("+ p.processname.tostring () +") Deny access to the full path! "); }        }    }         //process has not startedProcess Process =NewProcess (); 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 voidWatchprocess (Process process,stringaddress) {Processrestart Objprocessrestart=NewProcessrestart (process, address); Thread Thread=NewThread (NewThreadStart (objprocessrestart.restartprocess)); Thread.    Start (); }   Public classprocessrestart{//Field    PrivateProcess _process; Private string_address; /// <summary>    ///constructor Function/// </summary>     PublicProcessrestart () {}/// <summary>    ///constructor Function/// </summary>    /// <param name= "process" ></param>    /// <param name= "Address" ></param>     PublicProcessrestart (Process process,stringaddress) {         This. _process =process;  This. _address =address; }      /// <summary>    ///Restart Process/// </summary>     Public voidrestartprocess () {Try        {             while(true)            {                 This. _process.                WaitForExit ();  This. _process. Close ();//to release a handle to a process that has exited                 This. _process. Startinfo.filename = This. _address;  This. _process.                 Start (); Thread.Sleep ( +); }        }        Catch(Exception ex) {Processwatcher Objprocesswatcher=NewProcesswatcher (); Objprocesswatcher.savelog ("restartprocess () error, the monitor has been canceled on the process ("+ This. _process. Id.tostring () +")("+ This. _process. Processname.tostring ()+"), the error description is:"+Ex.        Message.tostring ()); }    }}

Implementing a generic daemon in C #

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.