本章讨论我们笼统地归为“高级I/O”的各个函数和技术

 

套接字超时

有3种方法在涉及套接字的I/O操作上设置超时

1.调用alarm,它在指定超时时期满时产生SIGALRM信号

2.在select中阻塞等待I/O(select有内置的时间限制),以此代替直接阻塞在read或write调用上

3.使用较新的SO_RCVTIMEO和SO_SNDTIMEO套接字选项。

 

使用SIGALRM为connect设置超时

下面给出我们的connect_timeo函数,它以调用者指定的超时上限调用connect

 1 /* include connect_timeo */
 2 #include    "unp.h"
 3 
 4 static void    connect_alarm(int);
 5 
 6 int
 7 connect_timeo(int sockfd, const SA *saptr, socklen_t salen, int nsec)
 8 {
 9     Sigfunc    *sigfunc;
10     int        n;
11 
12     sigfunc = Signal(SIGALRM, connect_alarm);
13     if (alarm(nsec) != 0)
14         err_msg("connect_timeo: alarm was already set");
15 
16     if ( (n = connect(sockfd, saptr, salen)) < 0) {
17         close(sockfd);
18         if (errno == EINTR)
19             errno = ETIMEDOUT;
20     }
21     alarm(0);                    /* turn off the alarm */
22     Signal(SIGALRM, sigfunc);    /* restore previous signal handler */
23 
24     return(n);
25 }
26 
27 static void
28 connect_alarm(int signo)
29 {
30     return;        /* just interrupt the connect() */
31 }
32 /* end connect_timeo */
View Code

相关文章: