Directly on the code, refer to the UNIX environment advanced programming
1 voidDaemon ()2 {3 structRlimit RL;4Umask0);5 pid_t pid;6PID =fork ();7 if(PID <0 )8 {9Perror ("Fork Error");Ten return 0; One } A if(PID >0)/*Parent*/ - { -Exit0); the } - Else /* Child*/ - { - /* + * Standard input can still be used before closing the descriptor, standard output - */ + Setsid (); AGetrlimit (rlimit_nofile,&RL); atprintf"The max file num is%d: \ n", Rl.rlim_max);/*Setsid () has been separated from the control terminal*/ -printf"The max file num is%d: \ n", rlim_infinity); - if(Rl.rlim_max = =rlim_infinity) -Rl.rlim_max =1024x768; - - inti; in for(i=0; i<rl.rlim_max; i++) - Close (i); to intfd0, Fd1, fd2; +fd0 = open ("/dev/null", O_RDWR); -FD1 = DUP (0); theFD2 = DUP (0); *Openlog ("Hello", Log_cons, Log_daemon); $ }Panax Notoginseng}
Some like to fork on the above basis again, because the above sub-process is the first process of the whole reply, the first process to get a control terminal, daemon can not be connected with the terminal, so fork again, the first child process (the first fork produced by the process) exit, the latest child process ( The second fork-generated process) is not a reply to the first process is not eligible to get back to the control terminal.
Some also handle sighup signals, see Advanced Programming for UNIX environments for SIGHUP signals
The second method:
Direct access to the functions provided by Linux Daemon ()
1 #include <unistd.h>23int main ()4{5 Daemon (0,0); 6 while (1) {/ * does not end immediately */78 }9 }
Ok...
Two implementations of Daemons