生成守护进程的函数

2018-08-02  本文已影响0人  丶Em1tu0F

改写系统调用函数:

#include <unistd.h>
int daemon(int nochdir, int noclose);

DESCRIPTION
The daemon() function is for programs wishing to detach themselves from the controlling terminal and run in the background as system daemons.
If nochdir is zero, daemon() changes the process’s current working directory to the root directory ("/");
otherwise, If noclose is zero, daemon() redirects standard input, standard output and standard error to /dev/null; otherwise, no changes are made to these file descriptors.

void daemonize(int nochdir, int noclose)
{
    pid_t pid;
    int i;
    struct rlimit rl;
    int fd0, fd1, fd2;
    
    if(getppid() == 1)
        return;
    umask(0);
    if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
        exit(-1);
    if((pid = fork()) == -1)
        exit(-1);
    else if(pid > 0)
        exit(0);
    
    setsid();
    signal(SIGCHLD, SIG_IGN);
    signal(SIGTSTP, SIG_IGN);
    signal(SIGTTOU, SIG_IGN);
    signal(SIGTTIN, SIG_IGN);
    signal(SIGHUP, SIG_IGN);
    if((pid == fork()) == -1)
        exit(-1);
    else if(pid > 0)
        exit(0);
    
    if(nochdir == 0){
        if(chdir("/") < 0)
            exit(-1);
    }
    if(rl.rlim_max == RLIM_INFINITY)
         rl.rlim_max = 1024;
    if(noclose == 0){
        for(i = 0; i < rl.rlim_max; i++)
            close(i);
        fd0 = open("/dev/null", O_RDWR);
        fd1 = dup(0);
        fd2 = dup(0);
        if(fd0 != 0 || fd1 != 1 || fd2 != 2)
            exit(-1);
    }

    unmask(0);

}

getrlimit(RLIMIT_NOFILE, &rl)函数获取进程可打开的最大文件数+1。
RLIM_INFINITY 用来表示不对资源限制;

内核默认的硬限制rlim_max = 1024;

if(rl.rlim_max == RLIM_INFINITY)
         rl.rlim_max = 1024;
    if(noclose == 0){
        for(i = 0; i < rl.rlim_max; i++)
            close(i);

代码中即关闭从父进程继承下来的所有文件描述符。

上一篇下一篇

猜你喜欢

热点阅读