【问题标题】:Linux Daemon not workingLinux 守护进程不工作
【发布时间】:2014-12-05 10:27:02
【问题描述】:

我在 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);

任何帮助都会很棒! :)

【问题讨论】:

  • 使用库或脚本来做这种事情,不需要重新发明这个*。
  • 只需在 stderr 上放一个 fprintf 即可发现子进程退出的位置。

标签: c++ linux daemon


【解决方案1】:

我很确定您的子进程在 sid &lt; 0chdir("/") &lt; 0 if 语句中终止。在这些情况下,在退出前写入 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);
}

您需要包含 &lt;errno.h&gt;&lt;string.h&gt; 才能(分别)定义 errno 和 strerror。

问候

【讨论】:

  • 可怕的故事...如果您注释掉与 fork 相关的所有内容(调用本身和有关 pid 变量的检查)会发生什么?
  • “创建 SID 失败:-1”输出。
  • 我想我们找到了问题所在。检查 errno 以获得更详细的错误描述。如果您稍等片刻,我将扩展我的答案以涵盖详细的错误报告。
最近更新 更多