First, The Guardian process
Daemons, also known as daemon Processes (daemon)
It differs from the normal background process in the following three points
1, the daemon process from the session, and the normal background process is not necessarily
2, the daemon is not controlled by the terminal
3, daemon process is the background process, the latter process is different from the daemon
Using the PS AXJ command to view the processes in the system, the process of tpgid a column of-1 (these processes do not have a control terminal) is the daemon.
Second, the realization
The steps to create the daemon are as follows:
1. Call Umask to set "File mode creation mask" to 0
Since the parameters received by the umask are reversed, the 0 is the largest one, which is the maximum permission for the program.
2. Fork first, then let the parent process exit
This is because the process to be set up as a daemon cannot make the lead process in the original process group, so the purpose of fork is to create a child process, so that the child process must not be the leader process, and then the parent process is useless.
3. Call SetID to create a new session
At this point, the process will become the first process of the new session (also the leader process)
4. Change the current working directory to the root directory
5. Close the unwanted file descriptor
6. Ignoring Sigchild signal
The implementation code is as follows:
650) this.width=650; "title=" 1.png "alt=" Wkiom1epf2qwn4zxaaesa_0nhgo281.png "src=" http://s4.51cto.com/wyfs02/M00/ 84/66/wkiom1epf2qwn4zxaaesa_0nhgo281.png "/>
After running, perform PS AXJ
Find the process that was just
650) this.width=650; "title=" 2.png "alt=" Wkiom1epgcpj6sgjaaacjnol6jk435.png "src=" http://s1.51cto.com/wyfs02/M01/ 84/66/wkiom1epgcpj6sgjaaacjnol6jk435.png "/>
You can also see that its parent process is process 1th, so the daemon is also an orphan process
But it's important to note that we don't need to build this wheel when we actually use it. There are ready-made functions
Daemon (0, 0) can turn the current process into an orphan process
Three, fork () two times the reason
Usually the implementation of daemon is different from the implementation of the above: fork () called two times, let the second fork to create a child process as a daemon.
This is because if you fork only once, then it is possible to have this situation:
After the first fork, the parent process is detached, when the child process becomes the first session, the child process may open a control terminal again, once this happens, the process is no longer a daemon, because it is again controlled by the terminal
Therefore, if you fork again, then this time the resulting child process will not be the first session, so it is impossible to open the terminal, so usually with this second fork out of the child process as a daemon
Daemons in Linux