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