[Zz] How do I run a program in daemon mode?

Source: Internet
Author: User
How do I run a program in daemon mode?
A program running in daemon mode has nothing to do with the console during its operation, that is, it is not affected by the console signal. It continues to run after the console exits, and other non-daemon programs will be affected by console operations, and is forcibly exited when the console exits. Therefore, most network service programs run in daemon mode.

You can add the following statement during program initialization, and the program will run in daemon mode:/** // * generate a new process and exit the original main process */
If (Fork () Exit (0 );
/** // * Close console handles such as stdin, stdout, and stderr */
For (n = 0; n <3; n ++) Close (N );
/** // * Point stdin, stdout, and stderr to/dev/null */
Open ("/dev/null", o_rdonly );
Dup2 (0, 1 );
Dup2 (0, 2 );
/** // * Set tty I/O attributes */
If (n = open ("/dev/tty", o_rdwr)> 0 )...{
IOCTL (n, tiocnotty, 0 );
Close (N );
}
/** // * Create a new session to make the current process a leader of process greoup */
Setsid ();
/** // * Generate a new process and exit the generated process. The new process has run in daemon mode */
If (Fork () Exit (0 );

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.