#include <sys/stat.h>#include<fcntl.h>/*bit-mask values for ' flags ' argument of Becomedaemon ()*/#defineBd_no_chdir * */Don ' t CHDIR ("/") */#defineBd_no_close_files/* Don ' t CLOSE all open FILES */#defineBd_no_reopen_std_fds/* Don ' t REOPEN stdin, stdout, andstderr to/dev/NULL*/#defineBd_no_umask0 010/* Don ' t do a umask (0) */#defineBd_max_close 8192/* Maximum file descriptors to CLOSE ifsysconf (_sc_open_max) isIndeterminate * *intBecomedaemon (intFlags/*Returns 0 On success, 1 on Error*/{ intMaxfd, FD; Switch(Fork ())/*Become background Process*/ { Case-1:return-1; Case 0: Break;/*Child falls through ...*/ default: _exit (exit_success);/*While parent terminates*/ } if(Setsid () = =-1)/*become leader of new session*/ return-1; Switch(Fork ()) {/*ensure we is not session leader*/ Case-1:return-1; Case 0: Break; default: _exit (exit_success); } if(! (Flags &bd_no_umask0)) Umask (0);/*Clear file Mode creation Mask*/ if(! (Flags &Bd_no_chdir)) ChDir ("/");/*Change to root directory*/ if(! (Flags & Bd_no_close_files)) {/*Close all open files*/maxfd=sysconf (_sc_open_max); if(Maxfd = =-1)/*Limit is indeterminate ...*/maxfd= Bd_max_close;/*So take a guess*/ for(FD =0; FD < MAXFD; fd++) Close (FD); } if(! (Flags &Bd_no_reopen_std_fds)) {Close (Stdin_fileno); /*Reopen Standard FD ' s to/dev/null*/FD= Open ("/dev/null", O_RDWR); if(FD! = Stdin_fileno)/*' fd ' should be 0*/ return-1; if(Dup2 (Stdin_fileno, stdout_fileno)! =Stdout_fileno)return-1; if(Dup2 (Stdin_fileno, stderr_fileno)! =Stderr_fileno)return-1; } return 0;}
Linux Daemon Process creation process