守护进程()有任何缺点吗?

时间:2017-05-02 19:40:41

标签: c++ c linux daemon

与使用fork(), setsid(), umask(),等显式函数相比,使用C函数daemon()对Linux守护进程有任何安全性或稳定性缺点(除了无法设置所有守护进程参数)?

我想知道为什么要写

#include <sys/types.h>
#include <sys/stat.h>
#include <cstdio>
#include <cstdlib>
#include <fcntl.h>
#include <cerrno>
#include <unistd.h>
#include <syslog.h>
#include <string>


int main()
{
    //Set our Logging Mask and open the Log
    setlogmask(LOG_UPTO(LOG_NOTICE));
    openlog(DAEMON_NAME, LOG_CONS | LOG_NDELAY | LOG_PERROR | LOG_PID, LOG_USER);

    syslog(LOG_INFO, "Entering Daemon");

    pid_t pid, sid;

   //Fork the Parent Process
    pid = fork();

    if (pid < 0) 
        exit(EXIT_FAILURE);

    //We got a good pid, Close the Parent Process
    if (pid > 0) 
        exit(EXIT_SUCCESS);

    //Change File Mask
    umask(0);

    //Create a new Signature Id for our child
    sid = setsid();
    if (sid < 0) 
        exit(EXIT_FAILURE);

    //Change Directory
    //If we cant find the directory we exit with failure.
    if ((chdir("/")) < 0) 
        exit(EXIT_FAILURE);

    //Close Standard File Descriptors
    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);

    while (true)
    {
        sleep(5);

        //Do something
    }

    closelog ();
}

而不是

#include <unistd.h>

int main()
{
    daemon(0, 0);

    while (true)
    {
        //Do something

        sleep(5);
    }
}

1 个答案:

答案 0 :(得分:2)

根据联机帮助页,它不在POSIX中,因此您总是冒着存在的风险。

否则,不。