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