简体   繁体   English

如何使用SIGINT在C语言中使用signal()函数

[英]How function signal() works in C with SIGINT

#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 ") ;
}

I am try to learn handle signals in c. 我试图学习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? 我知道当我按Control-c函数f执行该代码时,将执行并中断循环。但是当我反复快速按Control-c命令睡眠时,将不会执行。为什么?

On receiving a signal the call to sleep() is interupted. 收到信号后,对sleep()的调用会中断。

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
}

From man sleep ( Italics by me): man sleep (我的斜体字 ):

RETURN VALUE 返回值

Zero if the requested time has elapsed, or the number of seconds left to sleep, if the call was interrupted by a signal handler . 如果请求的时间已过,则为零;如果信号被信号处理程序中断 ,则为睡眠状态的秒数。

The short story is that sleep() will be interrupted and return when a signal is caught. 简而言之,当捕获到信号时,sleep()将被中断并返回。 The return value of sleep will tell you how many seconds it had left before it should have returned were it not interrupted. 睡眠的返回值将告诉您如果不中断睡眠,应该返回多少秒。

Certain functions get interrupted and returns when a signal is caught. 某些功能被中断并在捕获信号后返回。 This varies with your platform, and how a signal handler is installed. 这取决于您的平台以及信号处理程序的安装方式。 (And on linux it'll depend on the compilation flags used when installing a signal handler using signal(). See the documentation here and here ) (在linux上,将取决于使用signal()安装信号处理程序时使用的编译标志。请参见此处此处的文档)

In signal the handler is at hook point. 在信号中,处理程序在挂钩点。 It will call when the signal is arrived. 信号到达时它将调用。 After calling it starts executing from the next line from where it was called. 调用后,它从被调用的下一行开始执行。

So in your example, when signal (SIGINT) arrives this hooked to the handler f , once the f finished it will again go into the loop. 因此,在您的示例中,当信号(SIGINT)到达时,该信号已钩接到处理程序f,一旦f完成,它将再次进入循环。

( Note that there is no exit or abort from the handler f, only when it will return to the next line of execution in loop ) (请注意,只有当处理程序f返回到循环中的下一行执行时,它才不会退出或中止)

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

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