如何使用SIGINT在C语言中使用signal()函数 [英] How function signal() works in C with SIGINT

查看:415
本文介绍了如何使用SIGINT在C语言中使用signal()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>  
#include <signal.h>

void f( int );

int main () {
    int i ;
    signal ( SIGINT , f) ;
    for (i =0; i <5; i ++) {
        printf ( " hello \n " ) ;
        sleep (10) ;
    }
}

void f( int signum ){
    //signal ( SIGINT , f) ;
    printf ( " OUCH !\n ") ;
}

我正在尝试学习c中的句柄信号. 在上面的代码中,我无法理解功能信号的工作方式. 我知道当我按Control-c函数f执行该代码时,将执行并中断循环.但是当我反复快速按Control-c命令睡眠时,将不会执行.为什么?

I am try to learn handle signals in c. In code above i could not understand the way that function signal works. I understand that when i execute this code when i press control-c function f will be executed and would interrupt the loop.But when i press repeatedly and quickly control-c command sleep would not be executed .Why?

推荐答案

在收到信号后,对sleep()的调用会中断.

On receiving a signal the call to sleep() is interupted.

要对此进行可视化,请按如下所示修改代码:

To visualise this modify the code as follows:

unsigned seconds_left = 10;
while (0 < (seconds_left = sleep(seconds_left)))
{
  printf("Woke up with still %us to sleep, falling asleep again ...\n", seconds_left
}

来自 man sleep (斜体字):

返回值

如果请求的时间已过,则为零,或者剩余的秒数 如果呼叫被信号处理程序中断,则进入睡眠状态.

Zero if the requested time has elapsed, or the number of seconds left to sleep, if the call was interrupted by a signal handler.

这篇关于如何使用SIGINT在C语言中使用signal()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆