Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restart application on unhandled exception

Is it possible to have a program restart automatically if it crashes?

Something like:

  1. An unhandled exception is thrown.
  2. Release all resources allocated by process.
  3. Start over and call main.

I would like this behavior for a server application I'm working on. If clients miss use the server it can get a std::bac_alloc exception, in which case I would like the server to simply restart instead of crashing and shutting down, thus avoiding manual startup.

like image 649
ronag Avatar asked May 17 '11 21:05

ronag


4 Answers

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.

like image 115
T.E.D. Avatar answered Nov 12 '22 16:11

T.E.D.


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.

like image 26
Rob Kennedy Avatar answered Nov 12 '22 15:11

Rob Kennedy


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.)

like image 3
user258808 Avatar answered Nov 12 '22 15:11

user258808


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 image 1
Christian Rau Avatar answered Nov 12 '22 16:11

Christian Rau