簡體   English   中英

Linux守護程序不起作用

[英]Linux Daemon not working

我已經在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 < 0chdir("/") < 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);
}

您需要包括<errno.h><string.h>以便分別定義errno和strerror。

問候

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM