[工作點滴] Daemon應用於Linux嵌入式系統實作

Daemon應用於Linux嵌入式系統實作

Daemon(或是service)對有玩linux的同好應該是耳熟能詳的東西,Daemon大陸翻譯為守護進程,而我在台灣找網站沒有找到什麼特別的翻譯,在Devin Watson先生的Linux Daemon Writing HOWTO中,有做詳細的入門簡介及一個範例,我透過這個範例將目前專案的幾個程序做了一個小改變,如此可以達到常駐於系統背景的功能,以下是我的一個程式片段,可供各位參考應用。

int main(void)

{

    char message[20];  



    // Process ID and Session ID  

    pid_t pid, sid;  



    // Fork off the parent process.  

    pid = fork();  

    if (pid < 0) {  

            exit(EXIT_FAILURE);  

    }  



    // If we got a good pid, then we  

    // can exit the parent process.  

    if(pid > 0) {  

            exit(EXIT_SUCCESS);  

    }  



    // Change the file mode mask  

    umask(0);  



    // Open any logs here  

      

    // Create a new SID for the child process.  

    sid = setsid();  

    if(sid < 0) {  

            exit(EXIT_FAILURE);  

    }  

      

    // Change the working directory.  

    if((chdir("/")) < 0) {  

            exit(EXIT_FAILURE);  

    }  

      

    // Close out the standard file descriptors.  

    close(STDIN_FILENO);  

    close(STDOUT_FILENO);  

    close(STDERR_FILENO);  



    // Daemon-specific initialization goes here  

    // Set the GPIO.  

    // 這個部分是我所寫的初始化GPIO的應用程式。  

    system("/usr/sbin/setgpio -il");  



    while(1){  

            // 這個部份是透過網路上找的另一個程式,  

            // 如果可以透過system,去取得回應值並將之存於一個Buffer中  

            // 還蠻好用的。  

            // Get the status.  

            my_system("/usr/sbin/getgpio --status", message, 20);  

            if(message[17]=='0'){  

                    system("/usr/sbin/setgpio -ol");  

            }  

            else if(message[17]=='1'){  

                    system("/usr/sbin/setgpio -oh");  

            }  



            // Sleep for 5sec.  

            sleep(5);  

    }  



return 0;  

}


Comments & Feedback