为什么控制台上没有信号处理输出? [英] Why no output on console on signal handling?
问题描述
我正在Unix环境下的Advanced Programming中尝试此程序.
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;
}
我正在使用Ubuntu 11.10.我用gcc编译程序,然后按照书中的说明运行a.out.
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
$./a.out& [1]+ 1345
$ kill -USR1345
$ kill -USR1 1345
但是没有打印输出.该程序一直在背景中运行,我必须杀死它.
But there is no output printed. The program keeps running in backgound and I have to kill it.
我尝试过的其他事情:
-
试图处理SIGINT以查看在后台运行程序是否引起问题.仍然没有输出.
Tried handling SIGINT to see if running program in background is causing problems. Still no output.
下载了FreeBSD的最新版本,并尝试了相同的程序,但是存在相同的问题.
Downloaded latest release of FreeBSD and tried the same program on it, but with same problem.
我在设置信号处理程序之前放了一个printf语句:
I put a printf statement before setting signal handler:
int main(){
printf("printf is working...");
//exit(0);
if(signal(SIGUSR1, handler) == SIG_ERR)
...
注释exit()时,没有输出.当我取消注释时,将输出输出.
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:建议不要使用sigaction().我正在学习Unix编程,而不是构建任何实际的应用程序.
PS: Don't suggest using sigaction(). I am learning Unix Programming, not building any practical application.
推荐答案
printf
的输出被缓冲.这意味着它将存储在内存中,直到刷新到输出为止.刷新printf
中的文本的最佳方法是用换行符结束文本.您也可以使用fflush
功能手动刷新.
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.
但是,应注意,在信号处理程序中使用printf
和fflush
之类的输出函数并不安全.
However, you should be cautioned that using output functions like printf
and fflush
is not considered safe in signal handlers.
这篇关于为什么控制台上没有信号处理输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!