A daemon is a process that runs in the background, not connecting to any controlling terminal. Daemons are normally started at boot time, are run as root or some other special user (such as apache or postfix), and handle system-level tasks. As a convention, the name of a daemon often ends in d (as in crond and sshd), but this is not required or even universal.
守护进程运行在后台,并且不与任何的控制终端连接。守护进程一般在系统启动时启动、以root或者其他特殊的用户运行、处理系统级别的任务。按照惯例,守护进程的名字以字母d结尾,但这不是必须的,也不通用。
A daemon has two general requirements: it must run as a child of init and it must not be connected to a terminal.
In general, a program performs the following steps to become a daemon:
一般而言,一个应用程序执行以下几步,就可以成为一个守护进程:
1. Call fork(). This creates a new process, which will become the daemon.
调用fork(),产生一个子进程(这个子进程会成为守护进程)
2. In the parent, call exit(). This ensures that the original parent (the daemon’s grandparent) is satisfied that its child terminated, that the daemon’s parent is no longer running, and that the daemon is not a process group leader. This last point is a requirement for the successful completion of the next step.
父进程调用exit()函数
3. Call setsid(), giving the daemon a new process group and session, both of which have it as leader. This also ensures that the process has no associated controlling terminal (as the process just created a new session and will not assign one).
子进程调用setsid(void)函数
4. Change the working directory to the root directory via chdir(). This is done be‐ cause the inherited working directory can be anywhere on the filesystem. Daemons tend to run for the duration of the system’s uptime, and you don’t want to keep some random directory open and thus prevent an administrator from unmounting the filesystem containing that directory.
改变工作目录到根目录(/)
5. Close all file descriptors. You do not want to inherit open file descriptors, and, unaware, hold them open.
关闭所有的文件描述符(除非你意识你到为什么这么做)
6. Open file descriptors 0, 1, and 2 (standard in, standard out, and standard error) and redirect them to /dev/null.
将文件描述符0, 1, 和 2重定向到/dev/null
Following these rules, here is a program that daemonizes itself:
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/fs.h>
int main (void)
{
pid_t pid;
int i;
/* create new process */
pid = fork ();
if (pid == −1)
return −1;
else if (pid != 0)
exit (EXIT_SUCCESS);
/* create new session and process group */
if (setsid () == −1)
return −1;
/* set the working directory to the root directory */
if (chdir ("/") == −1)
return −1;
/* close all open files--NR_OPEN is overkill, but works */
for (i = 0; i < NR_OPEN; i++)
close (i);
/* redirect fd's 0,1,2 to /dev/null */
open ("/dev/null", O_RDWR); /* stdin */
dup (0); /* stdout */
dup (0); /* stderror */
/* do its daemon thing... */
return 0;
}