How To Create A Daemon In Linux?


Recently we struck up with a problem. The problem is to run a script continuously in background and continuously check for a folder content changes. If any modifications are done in that folder, the script once again should start one more script. We thought of doing this by using crontab. But the problem with crontab is we have to wait at least one minute to run our script. One minute is too long for my requirement. We require a solution which runs continuously in background at every micro second, it should be similar to a normal Linux daemon such as httpd, ssh, ftp etc. I have searched in Google for creating daemons in Linux. But most of the people suggested to write a daemon in C language, which is alien to me(I have learnt C language some 9 years back but now totally forgot it :( ). Here is one such link which will describe you how to create a daemon in Linux using C programming. 

I went through many documentations and other stuff but come to a conclusion to go with Shell script. Which will work same as daemon. Here is the code for the daemon which we accomplish using while loop

while true;
if [ -f /testing/*.txt ]
echo "file created"
mv /testing/*.txt /tst/

This while loop continuously runs because we give condition as true for this while loop and then written a if statement what to do. Once you create above script there are other points to mention, such as below once to make above script as a daemon..

So how to run the above script?
Ans : Use nohup when running the script. For those people who don't know nohup command here is the explnation. 
nohup is a command to run a program thought you logout from the machine. For example here is my script with nohup. 

nohup sh 

But some times this will not work. At that time run this script from crontab once and then remove the entry from crontab. 

So how to make this permanent?
Ans : Its simple. keep your script in /etc/init.d with execute permissions

cp /path/to/script/ /etc/init.d/
chmod +x /etc/init.d/

Then create a link file to this script to the corresponding run-level. This is required at the time of booting.

ln -s /etc/init.d/ /etc/rc.d/rc3.d/
ln -s /etc/init.d/ /etc/rc.d/rc3.d/

What are those above two command will do?
Ans : The S43 will tell the system to start the script as 43 script when it boots up. 
The K43 will tell the system to shutdown cleanly when you do a shut down. 

Please share your thoughts if you have better idea to do it:-)

  • Like the post? Please Subscribe to free RSS feed to get updates
  • Archive

    Translate this page


    The Linux Juggernaut | Copyright 2006-2009 Surendra Kumar Anne | Surendra's Home Page | Give us feedback how we are doing, Click here