alarm函数可以用于防止读阻塞。
但如果系统调用是自动重启动的,当从SIGALRM信号处理程序返回时,read并不被中断。在这种情形下,设置时间限制不起作用。
一、源代码:
cat -n 10_10.c
1 #include "apue.h"
2
3 static void sig_alarm(int sig_no);
4
5 int main()
6 {
7 int n;
8 char line[MAXLINE];
9
10 if (signal(SIGALRM,sig_alarm) == SIG_ERR){
11 err_sys("signal SIGALRM handler creation error");
12 }
13
14 alarm(10);
15
16 if ((n=read(STDIN_FILENO,line,MAXLINE)) < 0)
17 err_sys("read error");
18
19 alarm(0);
20
21 write(STDOUT_FILENO,line,n);
22 exit(0);
23 }
24
25
26
27 static void sig_alarm (int sig_no)
28 {
29
30 }
2.编译及运行结果:
gcc -Wall -ggdb3 10_10.c -o purpose_of_alarm
In file included from apue.h:132,
from 10_10.c:1:
error.c: In function `err_doit':
error.c:121: warning: implicit declaration of function `vsnprintf'
error.c:123: warning: implicit declaration of function `snprintf'
./purpose_of_alarm
read error: Interrupted system call