create daemon - turn


Link: https://www.zhihu.com/question/38609004/answer/77190522

A daemon is a process (such as input, output, etc.) running in the background that is not controlled by a terminal. General network services are run as a daemon. There are two main reasons why the daemon process is separated from the terminal: (1) The terminal used to start the daemon process needs to perform other tasks after the daemon process is started. (2) (If other users log in to the terminal, the error message of the previous daemon process should not appear) The signals (such as interrupt signals) generated by some keys on the terminal should not respond to any daemons previously started from the terminal. process affects. Be aware of the difference between a daemon process and a background running program (ie, a program that is added & started).

The process of creating a daemon:

1. Call fork to create a child process. The parent process terminates, leaving the child process to continue executing in the background.
2. The child process calls setsid to generate a new session and loses the control terminal. Call setsid() to make the child process process become the new session leader and the new process leader, and lose control of the terminal at the same time.
3. Ignore the SIGHUP signal. The termination of the session leader process will send this signal to other processes, causing other processes to terminate.
4. Call fork to create a child process. The child process terminates, and the child child process continues to execute. Since the child child process is no longer the session leader, the process is prohibited from reopening the controlling terminal.
5. Change the current working directory to the root directory. Usually the working directory is changed to the root directory, so that the process's startup directory can also be unmounted.
6. Close open file descriptors, open an empty device, and copy to standard output and standard error. Some library functions that avoid calling still output information to the screen.
7. Reset the file creation mask to clear the file creation mask inherited from the parent process and set it to 0.
8. Use the openlog function to establish a connection to syslogd.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325388337&siteId=291194637