2014-10-10 19 views
0

我在C++中爲linux創建了一個守護進程,但是,子進程似乎沒有做任何事情。一旦達到if(pid> 0)語句,一切似乎停止。 的Daemon.Start()的代碼如下:Linux守護進程無法正常工作

//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); 

任何幫助將是巨大的! :)

+0

使用庫或腳本來做這種事情,不需要重新發明這個輪子。 – 2014-10-10 09:44:15

+0

只需在stderr上放一個fprintf來發現子進程退出的位置。 – Claudio 2014-10-10 09:48:43

回答

1

我很確定您的子進程在sid < 0chdir("/") < 0 if語句中死亡。寫在這些情況下標準錯誤退出之前透露的問題是什麼:

//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>纔能有定義的錯誤號和字符串錯誤(分別)。

Regards

+0

我試過了,仍然沒有運氣。 – GenericMadman 2014-10-10 09:56:25

+0

可怕的故事......如果您評論與叉相關的所有內容(調用本身和有關pid變量的檢查),會發生什麼情況? – 2014-10-10 09:58:37

+0

輸出「無法創建SID:-1」。 – GenericMadman 2014-10-10 10:04:30