2013-07-18 61 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) –