2013-07-18 62 views
3
#include <stdio.h> 
#include <stdlib.h> 
#include <sys/signal.h> 
#include <string.h> 

void handler (int sig); 
int count; 

int main() { 

    struct sigaction act; 
    memset (&act, 0, sizeof (act)); 


    act.sa_handler = handler; 
    if (sigaction (SIGHUP, &act, NULL) < 0) { 
     perror ("sigaction"); 
     exit (-1); 
    } 

    int count = 0; 
    while(1) { 
     sleep(1); 
     count++; 
    } 

} 

void handler (int signal_number){ 
     printf ("count is %d\n", count); 
} 

我假設我正在做這個權利,我將如何去在命令行中呼叫嘆息?它需要打電話來打印我的計數。信號處理程序與嘆息

+0

爲什麼輸出總是「計數爲0」?爲什麼不是計數++處理 – DDukesterman

+0

你重新聲明瞭主數。 sig處理程序正在讀取全局「count」。 – aet

+0

修復了它。知道它俯瞰計數 – DDukesterman

回答

2

您可以使用kill -SIGHUP <pid>,其中<pid>是您的代碼的進程ID。

1

試試這個控制檯:

ps -a 

讀出你的程序

kill -s HUP target_pid 

Here you have手冊頁殺死的信號列表的PID。

編輯:更簡單,你可以使用killall:

killall -HUP nameofyourbinary 
4

技術上講,它是不安全的I/O操作的信號處理程序,更好地設置一個標誌,看它,並打印基礎上,旗。 在posix系統上,您應該能夠從命令行中「kill -HUP」來發送信號。

+0

+1用於提及I/O危險 –

+0

不僅printf,所有函數都做信號中斷,malloc(),這裏是[授權函數列表](http://man7.org/linux/man-pages/man7/ signal.7.html) –