Under normal conditions, we print the information generated by the program to the console in real-time display, if we want to tell a program to run as a daemon, we need to change the output direction of the information, it is directed to the configuration file set in the log file.
Converting a process to a daemon requires several steps:
1.fork a new process that exits the parent process.
2. redirect 0, 1, 23 file descriptors.
3. REDIRECT 1 to the log file.
voiddaemonize () {if(fork ()! =0)//to exit the parent processExit0); Setsid (); //set up a new sessionLOG (Log_level_info,"daemonized ... pid =%d", (int) Getpid ()); intFD =0; if(FD = open ("/dev/null", O_RDWR,0)) != -1)//open an empty device file{dup2 (fd, Stdin_fileno); //redirect 0 to/dev/nullDup2 (FD, Stdout_fileno);//redirect 1 to/dev/nullDup2 (FD, Stderr_fileno);//redirect 2 to/dev/null if(FD >Stderr_fileno) Close (FD); } if(G_conf->log_file! = NULL && (fd = open (G_conf->log_file, o_rdwr| o_append| O_creat,0))!= -1) {dup2 (fd, Stdout_fileno); //redirect 2 to the log file if(fd>Stderr_fileno) Close (FD); }}
Where the role of the DUP2 function is to copy the file descriptor negatively, copy the file descriptor from the first parameter to the file descriptor of the second parameter, that is, the second file descriptor points to the file that the first file descriptor points to, which means that the two descriptors share the same data structure, file structure, The reference count for this file struct is 2.
To set a process as a daemon