Background daemon Creation
Damon.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <signal.h>
#include <time.h>
#include <syslog.h>
Initializing the daemon daemon
int Init_diamon (void) {
int pid;//Process
int i;
Ignore terminal IO signal and stop signal
Signal (sigttou,sig_ign);
Signal (sigttin,sig_ign);
Signal (sigtstp,sig_ign);
Signal (sighup,sig_ign);
Creating a process
Pid=fork ();
if (pid>0) {
Exit (0);//End the parent process so that the child thread becomes a background process
}
else if (pid<0) {
return-1;
}
Setsid ()///////////////////////////////
To create a new child process again
Pid=fork ();
if (pid>0) {
Exit (0);
}
else if (pid<0) {
return-1;
}
Closes the inherited file descriptor
For (I=0;i<nofile;close (i++));
Change working directory so that it has no file system associated
ChDir ("/");
Set the file screen Word to 0
Umask (0);
Ignore signal
Signal (sigchld,sig_ign);
return 0;
}
int main (void) {
time_t now;
Init_diamon ();
Syslog (log_info| Log_user, "test daemon \ \ \");
while (1) {
Sleep (8);
Time (&now);
Syslog (log_info| Log_user, "System time: \t%s\t\n", CTime (&now));
}
}
Gcc-o Demon Demon.c
./demon
Verifying PS Aux|grep Demon
Tail-f/var/log/syslog
Aug 11:25:50 Server Demon: System time: #011Wed Aug ten 11:25:50 2016
Aug 11:25:58 SERVER Demon: System time: #011Wed Aug 11:25:58 2016
Aug 11:26:06 SERVER Demon: System time: #011Wed Aug 11:26:06 2016
Aug 10 11 : 26:14 SERVER Demon: System time: #011Wed Aug 11:26:14 2016
Aug 11:26:22 SERVER Demon: System time: #011Wed Aug 10 11:26:22 2016
Aug 11:26:30 SERVER Demon: System time: #011Wed Aug 11:26:30 2016