HowTo Restart a Daemon/Program in Linux if it Crashes/Killed

Most of security critical applications/services are pron to attacks and the first try is to kill/remove the process/application. Here in this post, im writing about the method to prevent the first try, to kill the service.

One method, is to restart the application when it is killed. For making an service/process to run as a daemon, In Linux, we can add a launching script at /etc/init.d/ directory, so that it will be started at the bootup init.

Here is a simple hello world program to demonstrate it.

int main() {
     while(1) { /* Continue forever as a daemon */
     printf("Hello world\n");
     sleep(1); /* Sleep for one minute */

Now compile it into hello.out and create a startup script to add it to init.d as below.

raj@08:39:10:$ gcc hello.c -o hello.out

while ! /home/raj/hello.out   #This will wait for the program to exit successfully .
echo “restarting”                  # Else it will restart.

Add this script /etc/init.d/ to start it at boot time. But now, we can test it without rebooting.

Provide execution permission to the script and run the script on one termnial.

raj@08:39:22:$ sudo chmod +x /home/raj/
raj@08:39:32:$ ./

Now you can see the program running and printing Hello world string once in one minute. Now open one more terminal and kill this process by finding its pid as below.

raj@08:40:07:$ pidof hello.out
raj@08:40:20:$ sudo kill 26685.

Now, you can see the process being started again.
Here is screenshot to give an overview.

Screenshot from 2012-12-02 08:40:54


Surely there will be may better ways, would like to know and if i come to know, i will update this. 🙂


Author: Shingu

Search in pursuit. Help me if you can.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s