所以这是我们在学习指南上遇到的一个问题:
一位 friend 想写一个有父进程和子进程的程序,允许父进程计算子进程中的事件。这个想法是 child 在每个事件中向 parent 发送一个信号(SIGUSR2)。父级有一个 SIGUSR2 的信号处理程序,每次处理程序执行时都会递增一个计数器。然后, parent 可以在 child 终止后打印计数。
你的 friend 试图在下面写一个原型(prototype)。 child 向 parent 发送 5 个信号。你的 friend 尝试在第 6 行和第 20 行调用 sleep 来模拟 parent 的工作和 child 的工作。他预计第 27 行打印的计数器值为 5。
然而,对于如下的 sleep 时间,他始终打印出值 1,而不是 5。
他问你为什么他得了 1,而不是 5。你的解释是什么?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
1 int counter = 0;
2
3 void handler(int sig)
4 {
5 counter++;
6 sleep(1); /* Parent does some work in the handler */
7 return;
8 }
9
10 int main()
11 {
12 int i;
13
14 signal(SIGUSR2, handler);
15
16 if (fork() == 0) { /* Child */
17 for (i = 0; i < 5; i++) {
18 kill(getppid(), SIGUSR2);
19 printf("sent SIGUSR2 to parent\n");
20 sleep(1); /* Child does some work */
21
22 }
23 exit(0);
24 }
25
26 waitpid(-1, NULL, 0);
27 printf("counter=%d\n", counter);
28 exit(0);
29 }
它对我来说看起来是正确的,当我获取代码并运行它时,它给我的输出是 5。所以我想我的问题是我没有看到某些东西,或者这是一个错字?我几个小时前给我的教授发了电子邮件,但仍然没有任何消息
最佳答案
从您的描述中不清楚哪个进程有哪个 sleep 时间,但如果 parent 的时间比 child 的时间长,那么 child 可能会在 parent 有机会处理所有信号之前终止。考虑这样一种极端情况,即在捕获到第一个信号之后, parent 进入休眠状态的时间太长,以至于 child 在 parent 醒来之前就退出了;在第一个之后它再也看不到任何信号。
关于c - Trouble with Computer Systems 2 期中学习指南,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12925080/