Why no output on console on signal handling?

匿名 (未验证) 提交于 2019-12-03 02:30:02

问题:

I was trying this program from Advance Programming in Unix Environment.

#include<stdio.h> #include<signal.h>  static void handler(int sig){     if(sig == SIGUSR1)         printf("handled user1 signal");     else if(sig == SIGUSR2)         printf("handles user2 signal");     else         printf("unkown signal"); }  int main(){      if(signal(SIGUSR1, handler) == SIG_ERR)         printf("can't handle signal SIGUSR1");     if(signal(SIGUSR2, handler) == SIG_ERR)         printf("can't handle signal SIGUSR2");     for(;;)         pause();     return 0; } 

I am using Ubuntu 11.10. I compile the program with gcc and then run a.out as indicated in the book.

$./a.out& [1]+ 1345

$ kill -USR1 1345

But there is no output printed. The program keeps running in backgound and I have to kill it.

Other things I have tried:

  1. Tried handling SIGINT to see if running program in background is causing problems. Still no output.

  2. Downloaded latest release of FreeBSD and tried the same program on it, but with same problem.

  3. I put a printf statement before setting signal handler:

    int main(){     printf("printf is working...");     //exit(0);     if(signal(SIGUSR1, handler) == SIG_ERR)     ... 

when exit() is commented, there is no output. When I uncomment it, the output is printed.

Please tell me what am I doing wrong in this?

PS: Don't suggest using sigaction(). I am learning Unix Programming, not building any practical application.

回答1:

The output from printf is buffered. That means it's stored in memory until flushed to the output. The best way to flush text in printf is to end the text with a newline. You can also flush manually with the fflush function.

However, you should be cautioned that using output functions like printf and fflush is not considered safe in signal handlers.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!