Ace source code analysis daemon (1) -- ACE: daemonize ()
The background service process does not belong to any terminal session, so it does not need to interact with any users. Many system services are implemented by the background service process, such as network services and printing. Windows and Unix are not uniform in implementing backend service processes. The names defined by windows are service and those defined by UNIX are daemon. Corresponding to the ace, for the UNIX platform ACE provides a static method named Ace: daemonize (), the process can become a background service process by calling this method; for the Windows platform, ACE provides a class named ace_nt_service. by calling a series of methods of this class, it can also become a background service process. The following describes the implementation of ACE: daemonize () and ace_nt_service in Ace.
ACE: daemonize (UNIX)
Refer to apue for a total of seven complete daemon process generation steps on the UNIX platform. Ace is not implemented at any time. The following describes these steps and the implementation code of ACE:
1. Fork new service process so that the parent process can exit. This ensures that the child process is not the process group leader.
Pid_t pid = ace_ OS: fork ();
If (pid =-1)
Return-1;
Else if (PID! = 0)
Ace_ OS: exit (0 );
2. Use setsid to create a session and set the sub-process as the process group leader. The sub-process does not have an associated control terminal.
Ace_ OS: setsid ();
Ace_ OS: Signal (sighup, sig_ign );
3. Fork a new service process again. This process is not the leader of the Process Group and cannot obtain control terminals again.
PID = ace_ OS: fork (program_name );
If (PID! = 0)
Ace_ OS: exit (0 );
4. Change the directory of the current file system. Otherwise, the system administrator cannot unload a file system.
If (pathname! = 0)
Ace_ OS: chdir (pathname );
5. Reset the access attribute of the file so that we have full control over everything we write.
Ace_ OS: umask (0 );
6. Close all file handles
If (close_all_handles)
For (INT I = ACE: max_handles ()-1; I> = 0; I --)
Ace_ OS: Close (I );
Return 0;
In addition, for the sake of security and robustness, even if the current process does not use stdin, stdout, and stderr, the three handles 0, 1, and 2 should be re-opened to correspond to/dev/null. But I don't know why Ace's implementation code does not include this step.