Automatically restart application when closes

I have a server application that I want to be running whenever the computer is running and usually this is the case, except sometimes I'll find it to have closed by itself.

Is there a bat or script I can run to monitor the application and restart it should it close?


Solution 1:

This doesn't always work (it sort of depends on how the program loads itself), but normally you can create a batch file like this:

@Echo off
:Start
NotePad
echo Program terminated at %Date% %Time% with Error %ErrorLevel% >> c:\logs\program.log 
echo Press Ctrl-C if you don't want to restart automatically
ping -n 10 localhost

goto Start

I've used Notepad as an example.

The lines

echo Press Ctrl-C if you don't want to restart automatically
ping -n 10 localhost

are just a delay (of 10 seconds) to give the user the chance to abort the process before it starts up again.

The line

echo Program terminated at %Date% %Time% with Error %ErrorLevel% >> c:\logs\program.log 

is not needed, but would log each time the program was closed to a file, so it might be useful to diagnose the problem The ErrorLevel may not tell you much, but a program is supposed to return 0 if it closed normally, and a non-zero message if it doesn't

Note, You mention that you program doesn't do anything if already running. That usually means that the application starts, detects that another copy is already running and shutdowns immediately. If that is the case ,and your program is running before your start this batch file, then the batch will loop round and attempt to start your program every ten seconds.

Solution 2:

Based on your answers above, what I suggest is that you put that command into a batch file, then set that batch file to run as a scheduled task every minute. There is virtually no overhead associated with this, and it ensures that your process gets stated regardless of whether you are around to even realize it stopped.

Solution 3:

I guess the right answer to this question depends on why you want to do it. Are you trying to solve accidental shut-down? Prevent casually "malicious" shut-down by users of the machine (e.g. employees closing monitoring software)? Prevent serious and skilled malicious attack? Are you trying to write malware yourself (in which case please sod off ;-))?

Also, as other commenters have mentioned, it would differ if you'd written a Windows service (for example)

Personally, I'd probably start by writing a second application and starting it the same way. Have both applications scan for each other periodically and restart if necessary - make sure you provide an easy way for the application to be legitimately closed though!

That said, and given your comment "sometimes I'll find it to have closed by itself" I would ACTUALLY start by trying to find out why it's closed...

Solution 4:

You can use a program called ReStartMe 2.0 [Mirror] does exactly that:

Monitors for processes and restarts them if they close.