simple example daemon code.
Code:
#include <stdio.h>
#include <sys/times.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <syslog.h>
int main()
{
pid_t pid,sid;
int fd,len;
if((pid=fork())<0){
perror("fork");
exit(EXIT_FAILURE);
}
if(pid>0){
puts("parent Exiting.");
exit(EXIT_SUCCESS);
}
/*====================DAEMON================================*/
puts("child process");
openlog("printime",LOG_PID,LOG_DAEMON);
if((sid=setsid()) <0){
syslog(LOG_ERR,"%s\n","Fork error");
exit(EXIT_FAILURE);
}
if((chdir("/"))<0){
syslog(LOG_ERR,"%s\n","chdir error");
exit(EXIT_FAILURE);
}
umask(0);
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
char *pnt;
time_t timebuf;
while(1){
time(&timebuf);
pnt=ctime(&timebuf);
len=(strlen(pnt)+1);
if((fd=open("/var/log/robsdate.log",O_CREAT|O_WRONLY|O_APPEND,0600)) <0){
syslog(LOG_ERR,"%s\n","open error");
exit(EXIT_FAILURE);
}
write(fd,pnt,len);
close(fd);
sleep(10);
}
closelog();
exit(EXIT_SUCCESS);
}
creating a daemon is simple.
The steps for creating a daemon are to fork a child process and then make the parent exit.
We need to disassociate the process from the current terminal session.Daemons are not interactive and so don't need a controlling terminal.
We call setsid to create a new session making the child process autonomous from for terminal session that it is invoked from,be that from a startup script or directly from the command line.
We then make the root directory the current working directory for the daemon.
(This is to ensure that a daemon dosn't prevent a mounted filesystem from being unmounted for whatever reason;i.e going to signle user mode etc.)
We then set its umask to 0 as the process's inherited mask may stop it from being able to make folders or files etc.
We then close down its inherited file descriptors that it will not need;i.e STDIN/OUT/ERROR,as the daemon will not echo characters to the terminal or take input from the command line.
when we enter an infinite loop to do whatever it is the daemon is going to do.
This should be enough for you to do your own research.
Also look into the openlog system call and how it is used to handle errors etc.
This is all paraphrased from Linux Programming by example by Kurt Wall.
A beginners book to C coding in LInux.
I still use it for reference from time to time(Obviously :0) )