To set a process as a daemon

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.