11303
题目
写一个小程序:循环读取一行输入并处理;当收到 SIGINT(Ctrl+C)时退出。要求:信号处理函数里只设置一个标志位,不做 I/O。
答案
c
#include <signal.h>
#include <stdio.h>
static volatile sig_atomic_t stop = 0;
static void handle_sigint(int sig) {
(void)sig;
stop = 1;
}
int main(void) {
signal(SIGINT, handle_sigint);
char line[256];
while (!stop && fgets(line, sizeof line, stdin) != NULL) {
fputs(line, stdout);
}
return 0;
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
信号处理函数只修改 volatile sig_atomic_t 类型的标志位;实际 I/O 留在主循环中完成。