How function signal() works in C with SIGINT

混江龙づ霸主 提交于 2019-12-25 01:29:29

问题


#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. 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?


回答1:


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
}

From man sleep (Italics by me):

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.




回答2:


The short story is that sleep() will be interrupted and return when a signal is caught. 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)




回答3:


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.

( 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 )



来源:https://stackoverflow.com/questions/24163563/how-function-signal-works-in-c-with-sigint

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!