1

While going through signals, I found that statement inside the handler was not printed. Here is the code I used:

#include"stdio.h"
#include"signal.h"
#include"unistd.h"
void handlerSIGINT(int sig)
{
    if(sig == SIGINT)
       printf("\nFinally caught SIGINT...");
}
int main()
{
    printf("Hello ... soon u'll receive a signal");
    if(signal(SIGINT, handlerSIGINT) == SIG_ERR)
    {
        printf("error in SIGINT  handling");
    }
    while(1)
        sleep(1);
    /*now press control + C to see the effect */
    return 0;
}

I got the following output when I run the program :

[root@node1 mytest]# ./a.out
^CHello ... soon u'll receive a signal
^CFinally caught SIGINT...
^CFinally caught SIGINT...
^CFinally caught SIGINT...
^Z
[1]+  Stopped                 ./a.out

My confusion is : When I first pressed "Ctrl+C" it didn't print the message in the handler i.e. "Finally caught SIGINT..." .But from the second time it started printing the message. Can anyone explain why is this happening...

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Mayank
  • 2,150
  • 1
  • 15
  • 13

1 Answers1

4
void handlerSIGINT(int sig)
{
    if (sig == SIGINT)
        printf("\nFinally caught SIGINT...");
}

Here in the signal handler, the output is not terminated by a new line, and by default, the standard output is line buffered, so it's only shown when the next time it sees the \n in the beginning. Change it to:

printf("Finally caught SIGINT...\n");

you would probably see the result as expected. Note, however, you should avoid using printf in a signal handler.

Community
  • 1
  • 1
Yu Hao
  • 119,891
  • 44
  • 235
  • 294