Is it possible to have a program restart automatically if it crashes?
Something like:
If you just catch the exception, it should be possible to just restart your server by internal programming logic without completely restarting the whole program.
Like @T.E.D., we've done this in an application we built. Our application is a windows service, so the helper program stops the service (eventually kill it, if it hangs) and start the service again.
I did something similar by implementing a watchdog. The watchdog ran as a service and would wait for a ping (called petting the dog) from the monitored process. If the monitored process died due to an exception, watchdog would cleanup and relaunch the application.
In case the application was not responding(no ping in a certain time) the watchdog would kill it and then restart it.
Here is a link to an implementation that you might want to use: http://www.codeproject.com/KB/security/WatchDog.aspx
(PS: I implemented my own version but I cannot post it here. I found this from a quick google search and have no first hand experience with this particular implementation.)
Let Windows be your watchdog. You can call ChangeServiceConfig2 to set the failure actions for your service. (If your server isn't a service, then you're doing it wrong.) Specify SERVICE_CONFIG_FAILURE_ACTIONS
for the dwInfoLevel
parameter, and in the SERVICE_FAILURE_ACTIONS structure, set lpsaActions
to an array of one or more SC_ACTION values. The type you want is SC_ACTION_RESTART
.
I've done this before in Windows by running said program from another program via a win32 CreateProcess call. The other program then waits on the "monitored" process to exit, and calls its CreateProcess()
again if it does. You wait for a process to exit by performing a WaitForSingleObject on the process' handle, which you get as one of the return values from your CreateProcess()
call.
You will of course want to program in some way to make the monitoring process shut itself and its child process down.