Linux System Programming读书笔记之deamon进程

来源:互联网 发布:怎么在淘宝上买小说 编辑:程序博客网 时间:2024/05/29 19:03

Deamon进程是一种在后台运行,不与任何控制终端有联系的进程。一般来说,deamon进程在系统boot阶段启动,用于处理系统级的任务。按照约定,deamon进程的名字一般以d结尾,比如crond,或者sshd。

Deamon进程有两个要求:(1)它必须是init进程的子进程;(2)它不能与任何终端有联系

一般来讲,一个程序可以通过以下步骤来成为一个deamon进程:

(1)调用fork(),这样会创建一个新的进程,接下来这个新进程会成为一个deamon进程

(2)在父进程中调用exit()。这样可以保证deamon进程不是它所在process group的leader。因为deamon进程创建时是和它的父进程在一个process group,而这个process group的leader不可能是刚刚创建的deamon进程。另外,由于deamon进程的父进程先于deamon进程终止,deamon进程的父进程会被系统设置为init进程,这样就满足了要求1.

(3)调用setsid(),给deamon创建一个新的process group和session。Deamon进程在这个process group和session中都是leader进程。这样就保证了deamon进程没有任何有联系的终端(因为进程刚刚创建了一个session,还没有被分配终端),这样就满足了要求2.

(4)调用chdir(),将工作目录变为根目录。这是因为deamon进程继承了父进程的工作目录,这个工作目录可能是文件系统的任意位置,而deamon进程会在系统内部一直运行,如果有一些目录在deamon进程中是被打开的,那么用户就无法unmount掉包含这个目录的文件系统。

(5)关掉所有的文件描述符。同样,被继承的文件描述符在deamon进程中会一直处于打开状态。

(6)打开文件描述符0,1,2(也就是标准输入流,标准输出流,标准错误流)并将它们重定向到/dev/null。 

如下示例代码摘自《Linux system programming》

#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){    pit_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    for(i = 0; i < NR_OPEN; i++)        close(i);    //redirect fd 0, 1, 2 to /dev/null    open("/dev/null", O_RDWR); //stdin    dup(0);                                   //stdout    dup(0);                                   //stderror    return 0;}




0 0