简体   繁体   English

在Linux中使用信号处理程序

[英]Using signal handler in linux

void f(int);
void main()
{
    signal(SIGINT, f);
    int i = 4;
    while(i < 1000)
    {
       sleep(10);
        i++;
     }
}

void f( int signum ){
    printf ( "OUCH \n") ;
}

if I hit "ctr C" while the program is looping, it prints out "OUCH" to the terminal. 如果在程序循环时按“ ctr C”,它将在终端输出“ OUCH”。 Is there anyway I can print out the current number that the program is looping using signal handler. 无论如何,我可以使用信号处理程序打印出程序正在循环的当前编号。

You can use global variables to store the value of the loop variable. 您可以使用全局变量来存储循环变量的值。 You can then access this variable from the signal handler. 然后,您可以从信号处理程序访问此变量。 Although you need to be very careful while doing this. 尽管在执行此操作时需要非常小心。

Please go through: Providing/passing argument to signal handler 请经历: 提供/传递参数给信号处理程序

Yes you can just add a static variable and keep the value in it in each iteration. 是的,您可以添加一个静态变量,并在每次迭代中将值保留在其中。

void f(int);
static int temp=0;
void main()
{

    int i = 4;
    while(i < 1000)
    {
       sleep(10);
        i++;
        temp=i;
     }
}

void f( int signum ){
    printf ( "OUCH %d \n", temp) ;


}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM