问题
#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