2017-01-30 40 views
0

我一直在考慮下面的代碼信號處理後臺進程和文件輸出

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <unistd.h> 
#include <signal.h> 
#include <sys/wait.h> 

FILE* file; 

void signal_handler(int _signal) { 
    switch(_signal){ 
     case SIGTERM: 
      fprintf(file, "Ouch, the Daemon Child was killed!\n"); 
      fflush(file); 
      abort(); 
     default: 
      fprintf(file, "So what?!\n"); 
      fflush(file); 
    } 
} 

int main() { 
    pid_t pid; 
    int status; 
    pid = fork(); 
    if(pid != 0) { 
     // parent 
     waitpid(pid, &status, WNOHANG); // daemonize the child 
    } else { 
     // child 
     signal(SIGTERM, signal_handler); 
     file = fopen("daemon.txt", "w"); 
     while(1) { 
      sleep(1); 
      fprintf(file, "Daemon child is alive.\n"); 
      fflush(file); 
     } 
    } 
    return 0; 
} 

和我的預期,我可以找到在daemon.txt字符串Ouch, the Daemon Child was killed!末,sudo kill -KILL後。然而,這種情況並非如此。我的錯在哪裏?

+0

如果我正確理解你的代碼,當進程收到SIGTERM時,應該打印出「守護進程,守護進程子進程死亡!\ n」。但是,您向它發送SIGKILL。你在期待什麼? – schaiba

+0

我可以在哪裏找到kill信號的完整列表?我提到https://www.tutorialspoint.com/c_standard_library/c_function_signal.htm,但沒有SIGKILL – Fabio

+1

信號依賴於操作系統。作爲一個起點,看看這個:http://pubs.opengroup.org/onlinepubs/009695399/basedefs/signal.h.html,但最好是如果你引用你的操作系統的'signal.h'文件。 – schaiba

回答

1

您似乎在捕獲SIGTERM,然後發送SIGKILL,您沒有處理程序。如果您使用kill -TERM $pid而不是kill -KILL,您可能會看到您的預期輸出。