求助啊,信号方面的问题
#include<stdio.h>
#include<unistd.h>
#include<signal.h>
#include<stdlib.h>
static void sig_quit(int );
int main()
{
int i,sum;
signal(SIGALRM, sig_quit);
ualarm(1,1);
printf("hello\n");
for ( i = 0;i<5000000;i++)
{
sum = sum + i;
}
printf("%d\n", sum);
return 0;
}
static void sig_quit(int signo)
{
printf("after 5 seconds\n");
}
程序的输出
[root@localhost linuxshares]# ./a.out
hello
after 5 seconds
after 5 seconds
after 5 seconds
after 5 seconds
after 5 seconds
after 5 seconds
after 5 seconds
1642668640
1642668640
after 5 seconds
为什么会有输出两次sum的值啊
------解决方案--------------------
众所周知printf是带应用层buffer的,如果你main里的printf把1642668640\n放入buffer里,并且发现有\n,于是立即write写出, 此刻信号到来中断了main,那么信号处理函数将after 5 seconds\n追加到buffer里,又检测到\n,于是刷新整个buffer,于是write出1642668640\nafter 5 seconds\n。
我只能这么解释了。