开发者

How to make script/program to make it so an application is always running?

I have a simple .exe that needs to be running continuously.

Unfortunately, sometimes it crashes unexpectedly, and there's nothing that can be done for this.

I'm thinking of like a开发者_JAVA技巧 C# program that scans the running application tree on a timer and if the process stops running it re-launches it... ? Not sure how to do that though....

Any other ideas?


It's fairly easy to do that, but the "crashes unexpectedly, and there's nothing that can be done for this" sounds highly suspect to me. Perhaps you mean the program in question is from a third party, and you need to work around problems they can't/won't fix?

In any case, there's quite a bit of sample code to do exactly what you're talking about.


The first solution would be to fix your EXE, so it does not crash. If you can not fix it now, you probably need to add exception handling, so you can catch the exception, and not close the EXE.

Second solution is to write simple guard programm that will start your simple .exe and will monitor specific process handle. It will restart your program when it closes.


easiest way is to have you program see if an instance of itself is running and exit if it is. Set up a scheduled task to run it every couple of minutes.

class Program
{
    static void Main(string[] args)
    {
        if (IsRunning())
        {
            return;
        }
        else
        {
            for (int x = 0; x < 10; x++)
            {
                //Do Stuff
                System.Threading.Thread.Sleep(1000);
            }
        }
    }

    private static bool IsRunning()
    {

        Process[] P = Process.GetProcessesByName( Process.GetCurrentProcess().ProcessName  ) ;
        return P.Count() > 1;
    }
}


One trick occasionally employed by malware in days past was to have two processes that each monitor the currently running processes and restart the other process if it is terminated.

The System.Diagnostics namespace has classes which can help, particularly "Process".

For example

static Process[] Process.GetProcesses()

returns a list of all the currently running processes.

If your other process is not in this list, you just restart it with, for example

Process.Start()


Your program needs to initially start your target process itself (with Process.Start), then simply wait for it to terminate (with WaitForExit on object that is returned by Process.Start()). After that whole procedure is repeated.

This way you'd be sure that you are watching the process you are interested in, and you don't need to poll process list at all.

Process.Start() and WaitForExit() usage example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜