/* $begin counterprob */
#include "csapp.h"
int counter = 0;
void handler(int sig)
{
counter++;
printf("hander_counter = %d\n",counter);
sleep(1); /* Do some work in the handler */
return;
}
int main()
{
int i;
signal(SIGUSR2, handler);
if (Fork() == 0) { /* Child */
for (i = 0; i < 5; i++) {
kill(getppid(), SIGUSR2);
printf("sent SIGUSR2 to parent\n");
}
exit(0);
}
wait(NULL);
printf("counter=%d\n", counter);
exit(0);
}
/* $end counterprob */
增加了一些代码先看看啥情况
你会发现handler其实只被执行了两次,一次被接收后进入信号处理程序,然后有一个待处理信号跟在后面,后面多次发送同样的信号是默认丢弃的嚄.
/* $begin counterprob */
#include "csapp.h"
int counter = 0;
void handler(int sig)
{
counter++;
printf("hander_counter = %d\n",counter);
sleep(1); /* 这里代表可能做一些处理,假设这些处理花了1秒 */
return;
}
int main()
{
int i;
signal(SIGUSR2, handler);
if (Fork() == 0) { /* Child */
for (i = 0; i < 5; i++) {
kill(getppid(), SIGUSR2);
printf("sent SIGUSR2 to parent\n");
}
exit(0);
}
wait(NULL);
printf("counter=%d\n", counter);
exit(0);
}
/* $end counterprob */
信号处理程序是接收一个SIGUSR2执行完再接收下一个SIGUSR2,执行期间无论发送多少个都会被丢掉.你会发现如果去掉sleep,counter就正常了.但这样做不对啊,handler应该有事做才对.不能只用来count