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}