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.

1
  • Read signal(7). You are not allowed to call printf inside your signal handler - even if most of the time it seems to work. Nov 14, 2014 at 6:23

2 Answers 2

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

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


}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.