buffered printf issue

I wrote a little c code to test signal handler like following: I have a signal handler to capture the signal and print the signal name.
-----------------------------------------------

    
    
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <signal.h>
  4. #include <unistd.h>
  5.  
  6.  
  7. void sigroutine ( int dunno )
  8. {
  9. switch ( dunno )
  10. {
  11. case 1 :
  12. printf ( "Get a signal -- SIGHUP " ) ;
  13. break ;
  14. case 2 :
  15. printf ( "Get a signal -- SIGINT " ) ;
  16. break ;
  17. case 3 :
  18. printf ( "Get a signal -- SIGQUIT " ) ;
  19. break ;
  20. }
  21. return ;
  22. }
  23. int main ( int argc, char ** argv )
  24. {
  25. int c;
  26. printf ( "process id is %d " ,getpid ( ) ) ;
  27. signal ( SIGHUP, sigroutine ) ; /*set the signal handler.*/
  28. signal ( SIGINT, sigroutine ) ;
  29. signal ( SIGQUIT, sigroutine ) ;
  30. while ( 1 )
  31. {
  32. c = getchar ( ) ;
  33. printf ( "input %c" ,c ) ;
  34. }
  35. }

-------------------------------------------
then I run it in a shell window. Then I press Ctrl+C(sending SIGINT)
, however the sigroutine() doesn't output the message to screen until I press any key in the shell. It seems the sigroutine() is executed only after the getchar() in the main() is executed.

who can help explain it?

 

answer:

you stdout is likely line-buffered, meaning you should terminate the printf calls with a /n char OR fflush(stdout) after printing OR setbuf(stdout, NULL) before printing.

but what youre doing is wrong because youre not allowed to call stdio functions from signal handlers since they are not reentrant. like, the interrupted getchar() call may have left data structures in an indeterminate state, and your printf call in the siignal handler may then wrongly access them. solution: only write a flag (of type volatile sig_atomic_t) in a signal handler and let someone else check that flag and print the message. i nthis case the main() function

also, you should really use sigaction() without setting SA_RESETHAND because with just signal() some systems will deinstall your signal handler and reset the default signal action after the signal arrived the first time

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值