2015-04-07 92 views
0

我有這樣的代碼,以使守護程序在C:在後臺運行的Linux守護VS無限循環

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <sys/types.h> 
#include <sys/stat.h> 
#include <string.h> 

void main() { 
    FILE *fp= NULL; 
    pid_t process_id = 0; 
    pid_t sid = 0; 
    // Create child process 
    process_id = fork(); 
    // Indication of fork() failure 
    if (process_id < 0) 
    { 
    printf("fork failed!\n"); 
    // Return failure in exit status 
    exit(1); 
    } 
    // PARENT PROCESS. Need to kill it. 
    if (process_id > 0) 
    { 
    printf("process_id of child process %d \n", process_id); 
    // return success in exit status 
    exit(0); 
    } 
    //unmask the file mode 
    umask(0); 
    //set new session 
    sid = setsid(); 
    if(sid < 0) 
    { 
    // Return failure 
    exit(1); 
    } 
    // Change the current working directory to root. 
    chdir("/"); 
    // Close stdin. stdout and stderr 
    close(STDIN_FILENO); 
    close(STDOUT_FILENO); 
    close(STDERR_FILENO); 

    while (1) 
    { 
    // Do your thing 
    usleep(2000); 
    } 
} 

我可以編譯並運行此作爲./exampleOne,這將運行在後臺守護進程永遠。

現在相反,如果我有下面的例子:

#include <stdio.h> 
#include <stdlib.h 

void main() { 
    while (1) 
    { 

    // do your thing 
    usleep(2000); 
    } 
} 

然後運行它作爲./exampleTwo &。這現在也將作爲無限循環在後臺運行。

那有什麼區別?第二個是非常簡單的。叉/守護辦法

+0

爲什麼不創建一些腳本並在cron中運行它? :) –

+0

只是一個相關的事情:你應該安裝一個信號處理程序或事件有機會正常終止惡魔進程。 _「那有什麼區別?」_第一個例子自動將你的惡魔進程置於後臺。 –

+0

不同之處在於該示例二將僅響應每2秒的任何輸入或事件。你會接受嗎? –

回答

2

一個簡單的優點是程序員決定將發生叉它允許程序員提供了保證,當一個人返回,沒有錯誤的殼,守護程序啓動並運行。

在後臺運行會立即返回到shell,因此守護進程可能仍處於初始化階段,並且連接到它可能會失敗一段時間。