gpt4 book ai didi

c++ - daemon() 有什么缺点吗?

转载 作者:太空宇宙 更新时间:2023-11-04 08:04:34 27 4
gpt4 key购买 nike

是否使用 C 函数 daemon()与使用 fork()、setsid()、umask()、 等显式函数(除了无法设置所有守护进程参数之外)相比,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);
}
}

最佳答案

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

否则,没有。

关于c++ - daemon() 有什么缺点吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43745956/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com