C Programming of linux daemon

Source: Internet
Author: User

By using the code downloaded from the internet, the daemon process is successfully implemented. The original daemon process is very simple.

Execute in main Function

Init_daemon (); // initialize to Daemon

You can turn the process into a daemon process.

# Include
# Include
# Include
# Include
# Include

Void init_daemon (void)
{
Int pid;
Int I;

If (pid = fork ())
Exit (0); // It is the parent process and ends the parent process.
Else if (pid <0)
Exit (1); // fork failed, quit
// It is the first sub-process and continues execution in the background

Setsid (); // The first sub-process becomes the new session leader and process leader
// Separate it from the control terminal
If (pid = fork ())
Exit (0); // It is the first sub-process and ends the first sub-process.
Else if (pid <0)
Exit (1); // fork failed, quit
// The second sub-process. Continue
// The second sub-process is no longer the session leader

For (I = 0; I <NOFILE; ++ I) // close the opened file descriptor
Close (I );
Chdir ("/tmp"); // change the working directory to/tmp
Umask (0); // reset the file to create a mask
Return;
}

Related Article

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.