The concept of daemon and its creation method under Linux

0 Preface

I'm writing an HTTP server recently, and I plan to make it a daemon like an apache server to run in the background. At the time of writing, I found that the daemon process has a lot of particularities, and I hereby record it.

1 Daemon concept

The daemon in English is Daemon, and its etymology is the demigod and half-human elves in Greek mythology, responsible for silently guarding a person's soul from life to death. As the name suggests, daemon processes refer to processes that run in the background, do not occupy a terminal , and have a long life cycle (generally from boot to shutdown). Common daemon processes in Linux include ssh (remote login) and httpd (web service).

2 Create a daemon

The steps to create a daemon are as follows:

  1. Execute fork() to let the parent process exit and the child process to continue execution. The purpose of this is to ensure that the child process will not become the first process of the process group.
  2. The child process calls the setsid() function. In this way, a new session can be opened and the relationship with the terminal can be released.
  3. Execute a fork() again to ensure that the child process will not become the new conversation group leader. Under Linux, ensure that the process applies for a terminal.
  4. Clear the process umask to ensure the permissions of the Daemon process to create files and directories. (Students who are not sure about umask, please Baidu by yourself)
  5. (Optional) Close the file descriptor inherited by the daemon from the parent process. Because the daemon does not require a terminal, file descriptors such as standard input and standard output are useless and should be closed. Redirect to /dev/null after closing to prevent some library functions from using these file descriptors as standard input and output. Of course, this step is not mandatory. For example, sometimes the standard output can be redirected to the error log.

Guess you like

Origin blog.csdn.net/MoonWisher_liang/article/details/112384642