8. 常见的问题
$ netstatselect_restart:
if ((err = select(fdmax+1, &readfds, NULL, NULL, NULL)) == -1) {
if (errno == EINTR) {
// 某个 signal 中断了我们,所以重新启动
goto select_restart;
}
// 这里处理真正的错误:
perror("select");
}#include <unistd.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
int recvtimeout(int s, char *buf, int len, int timeout)
{
fd_set fds;
int n;
struct timeval tv;
// 设置 file descriptor set
FD_ZERO(&fds);
FD_SET(s, &fds);
// 设置 timeout 的数据结构 struct timeval
tv.tv_sec = timeout;
tv.tv_usec = 0;
// 一直等到 timeout 或收到数据
n = select(s+1, &fds, NULL, NULL, &tv);
if (n == 0) return -2; // timeout!
if (n == -1) return -1; // error
// 数据一定有在这里,所以调用一般的 recv()
return recv(s, buf, len, 0);
}
.
.
.
// 调用 recvtimeout() 的示例:
n = recvtimeout(s, buf, sizeof buf, 10); // 10 second timeout
if (n == -1) {
// 发生错误
perror("recvtimeout");
}
else if (n == -2) {
// 发生 timeout
} else {
// 从 buf 收到一些数据
}
.
.
.Last updated