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

BenMorel
  • 34,448
  • 50
  • 182
  • 322
seinta
  • 115
  • 1
  • 6
  • It is operating system specific. If on Linux, read [signal(7)](http://man7.org/linux/man-pages/man7/signal.7.html) then [Advanced Linux Programming](http://advancedlinuxprogramming.com/) – Basile Starynkevitch Jun 11 '14 at 13:00
  • 1
    Are you asking why `sleep` will not be executed after the signal? – egur Jun 11 '14 at 13:11
  • 2
    [POSIX manual page for signal()](http://pubs.opengroup.org/onlinepubs/9699919799/functions/signal.html) says *new applications should use [`sigaction()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigaction.html) rather than signal()*. – pmg Jun 11 '14 at 13:16

3 Answers3

3

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.

alk
  • 69,737
  • 10
  • 105
  • 255
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)

nos
  • 223,662
  • 58
  • 417
  • 506
0

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 )

Sandeep_black
  • 1,352
  • 17
  • 18