Writing a Simple Linux Daemon Program
I have decided to write a watcher daemon to watch a specified folder for any newly created files or folders. I did some googling and found that it was very simple to create a daemon program in Linux.
First you will need to create your source file and include the following header file:
#include <unistd.h>
In the main function you need to call daemon() like this:
int main() { if (daemon(0,0) == -1) err(1, NULL); while(1) { Do something here.... } }
In the while loop you can put your own code to perform a specific task.
To run the daemon when your system boots up edit the file /etc/init.d/rc.local and add the following line at the end of the file:
/usr/sbin/yourdaemon
note: make sure the you copied the file to /usr/sbin or else the file can not be found when the system is booting up.
The daemon function parameters, I have specifice 0 for the first paramter to use the root “/” folder instead of the working folder and the second parameter I have done the same which will redirect all standard input, output and errors to /dev/null.
Detailed information on how to use the daemon function can be found here.