linux學習 - 守護進程

這幾篇文章都是在做徐老師當年的書《操作系統 原理.技術與編程》裏面強調的若干個例子時的經歷,這些東西給大家共享一下


第一題,書裏面寫了1,2,3,4,5,6條,需要好好看看


守護進程代碼很簡單,如下


#include <unistd.h>
#include <sys/stat.h>
#include <sys/param.h>
#include <sys/types.h>
#include <signal.h>

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

void init_daemon(){
    pid_t pid;
    int i;
    if((pid = fork()) < 0) exit(1);
    if(pid > 0) exit(0);
    setsid();
    if((pid = fork()) < 0) exit(1);
    if(pid > 0) exit(0);
    for(i = 0; i < NOFILE; ++i){
        close(i);
    }   
    umask(0);
    chdir("/tmp");  // 這裏需要考慮成功與否,因爲有可能權限不足
    return;
}

int main(){
    FILE *p; 
    FILE *fp;
    char buf[256];
    init_daemon();
    while(1){
        sleep(30);
        if((fp = fopen("log.log", "a")) != NULL){
            p = popen("ps -f", "r");
            while(fgets(buf, sizeof(buf), p)!= NULL)
                fprintf(fp, "%s\n", buf);    
            fclose(p);  
            fclose(fp);
        }   
    }   
    return 0;
}

每30s寫一次log.log文件

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章