1
void f(int);
void main()
{
    signal(SIGINT, f);
    int i = 4;
    while(i < 1000)
    {
       sleep(10);
        i++;
     }
}

void f( int signum ){
    printf ( "OUCH \n") ;
}

if I hit "ctr C" while the program is looping, it prints out "OUCH" to the terminal. Is there anyway I can print out the current number that the program is looping using signal handler.

Termininja
  • 6,620
  • 12
  • 48
  • 49
stanlopfer
  • 73
  • 1
  • 2
  • 5
  • Read [signal(7)](http://man7.org/linux/man-pages/man7/signal.7.html). You are not allowed to call `printf` inside your signal handler - even if most of the time it seems to work. – Basile Starynkevitch Nov 14 '14 at 06:23

2 Answers2

1

You can use global variables to store the value of the loop variable. You can then access this variable from the signal handler. Although you need to be very careful while doing this.

Please go through: Providing/passing argument to signal handler

Community
  • 1
  • 1
vvvv
  • 135
  • 10
0

Yes you can just add a static variable and keep the value in it in each iteration.

void f(int);
static int temp=0;
void main()
{

    int i = 4;
    while(i < 1000)
    {
       sleep(10);
        i++;
        temp=i;
     }
}

void f( int signum ){
    printf ( "OUCH %d \n", temp) ;


}
Arnab Nandy
  • 6,472
  • 5
  • 44
  • 50