c++ - Linux 守护进程不工作

标签 c++ linux daemon

我已经在 C++ 中为 linux 创建了一个守护进程,但是,子进程似乎没有做任何事情。一旦到达 if(pid > 0) 语句,一切似乎都停止了。 Daemon.Start() 的代码如下:

//Process ID and Session ID
pid_t pid,sid;

//Fork off the Parent Process
pid = fork();
if(pid < 0)
    exit(EXIT_FAILURE);
//If PID is good, then exit the Parent Process
if(pid > 0)
    exit(EXIT_SUCCESS);

//Change the file mode mask
umask(0);

//Create a new SID for the Child Process
sid = setsid();
if(sid < 0)
{
    exit(EXIT_FAILURE);
}

//Change the current working directory
if((chdir("/")) < 0)
{
    //Log the failure
    exit(EXIT_FAILURE);
}

//Close out the standard file descriptors
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);

//The main loop.
Globals::LogError("Service started.");
while(true)
{
    //The Service task
    Globals::LogError("Service working.");
    if(!SystemConfiguration::IsFirstRun() && !SystemConfiguration::GetMediaUpdateReady())
    {
        SyncServer();
    }
    sleep(SystemConfiguration::GetServerConnectionFrequency()); //Wait 30 seconds

}

exit(EXIT_SUCCESS);

任何帮助都会很棒! :)

最佳答案

我很确定您的子进程在 sid < 0 中终止。或 chdir("/") < 0如果声明。在这些情况下,在退出之前写入 stderr 以揭示问题所在:

//Create a new SID for the Child Process
sid = setsid();
if(sid < 0)
{
    fprintf(stderr,"Failed to create SID: %s\n",strerror(errno));
    exit(EXIT_FAILURE);
}

//Change the current working directory
int chdir_rv = chdir("/");
if(chdir_rv < 0)
{
    fprintf(stderr,"Failed to chdir: %s\n",strerror(errno));
    exit(EXIT_FAILURE);
}

您需要包括 <errno.h><string.h>以便(分别)定义 errno 和 strerror。

问候

关于c++ - Linux 守护进程不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26296238/

相关文章:

c++ - unsigned long long 的确切大小应该是多少

c++ - 根据特征隐藏类模板实例

C++:获取2位数字的前一位

linux - 如何访问 ExecStop 或 ExecPostStop 中服务的返回码?

linux -/etc/sudoers 文件有问题但无法访问 root

linux - 如何使用 systemd 将应用程序作为守护进程运行?

c++ - Eigen + std::vector + OpenMP 内存泄漏

linux - shell脚本变量传递给awk并需要保留双引号

macos - 任何围绕从 OSX 守护进程启动 UI 的工作

php - 我可以启动一个脚本,使其独立于 Linux 上的父进程吗?