Steps of the daemon Function

Source: Internet
Author: User

1. fork

Call fork to terminate the parent process. If a process is started from the foreground using shell commands, when the parent process is terminated, shell considers that the command has been executed completely. This automatically enables sub-processes to run in the background. The child process inherits the process group number of the parent process, but the group number is different from its process number, so it is not the process group header, which is necessary to call setsid.

2. setsid

Setsid creates a new logon session. The process becomes the session header of the new session and the new process group leader. There are no control terminals.

3. Ignore the SIGHUP signal and fork again

In SVR4, when a session header process without a control terminal opens the terminal device, the terminal automatically becomes the control terminal of the session header. However, by calling fork for the second time, we can ensure that the child process generated this time is no longer the header of a session, so it does not obtain the control terminal. The SIGHUP signal must be ignored because when the session header ends, all processes in the session receive the SIGHUP signal.

4. Set the identifier for the error handling function

5. Change the working directory and clear the file mode to create a mask.

6. Close all open file descriptions

7. Use syslogd to handle errors

1 # define MAXFD 64
2 void Daemon ()
3 {
4 int I;
5 if (pid = fork ())! = 0)
6 exit (0 );
7 setsid ();
8 signal (SIGHUP, SIG_IGN );
9 if (pid = fork ())! = 0)
10 exit (0 );
11 chdir ("/");
12 umask (0 );
13 for (I = 0; I <MAXFD; ++ I)
14 close (I );
15}

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.