c - Signal handler statement not printed -


while going through signals, found statement inside handler not printed. here code 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 ... u'll receive signal");     if(signal(sigint, handlersigint) == sig_err)     {         printf("error in sigint  handling");     }     while(1)         sleep(1);     /*now press control + c see effect */     return 0; } 

i got following output when run program :

[root@node1 mytest]# ./a.out ^chello ... u'll receive signal ^cfinally caught sigint... ^cfinally caught sigint... ^cfinally caught sigint... ^z [1]+  stopped                 ./a.out 

my confusion : when first pressed "ctrl+c" didn't print message in handler i.e. "finally caught sigint..." .but second time started printing message. can explain why happening...

void handlersigint(int sig) {     if (sig == sigint)         printf("\nfinally caught sigint..."); } 

here in signal handler, output not terminated new line, , default, standard output line buffered, it's shown when next time sees \n in beginning. change to:

printf("finally caught sigint...\n"); 

you see result expected. note, however, you should avoid using printf in signal handler.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -