We have a mission-critical server program on top of Linux and we don\'t want others to terminate it accidentally. If somebody terminates it or it crashes, we want it to rest
You can restart your server from inside itself using fork. Oh the beauty of Unix.
Something like:
int result = fork();
if(result == 0)
DoServer();
if(result < 0)
{
perror(); exit(1);
}
for(;;)
{
int status = 0;
waitpid(-1, &status, 0);
if(!WIFEXITED(status))
{
result = fork();
if(result == 0)
DoServer();
if(result < 0)
{
puts("uh... crashed and cannot restart");
exit(1);
}
}
else exit(0);
}
EDIT:
It's probably wise to use the WIFEXITED
macro as test condition, which is more concise and portable (changed code accordingly). Plus, it fittingly models the semantics that we probably want.
waitpid
, given zero flags, won't return anything but either normal or abnormal termination. WIFEXITED
results in true
if the process exited normally, such as by returning from main
or calling exit
. If the process exited normally (e.g. because you requested that), one very probably does not want to keep restarting it until the end of days!