Tuesday, March 20, 2012

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.

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 daemon.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/daemon.sh /etc/init.d/
chmod +x /etc/init.d/daemon.sh

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/daemon.sh /etc/rc.d/rc3.d/S43daemon.sh
ln -s /etc/init.d/daemon.sh /etc/rc.d/rc3.d/K43daemon.sh

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

DISCLAIMER: The information provided on this website comes without warranty of any kind and is distributed AS IS. Every effort has been made to provide the information as accurate as possible, but no warranty or fitness is implied. The information may be incomplete, may contain errors or may have become out of date. The use of this information described herein is your responsibility, and to use it in your own environments do so at your own risk.

Copyright © 2012 LINUXHOWTO.IN

1 comment: