当前位置: 技术问答>linux和unix
关于unix 的 select
来源: 互联网 发布时间:2016-01-02
本文导语: 想用select实现非阻塞的程序。只有把超时设为NULL, 也就是select阻塞时, 才能接收到客户端程序的连接。 如果把超时设定为2秒, 就检测不到客户端的连接。这是为什么? struct timeval tv; fd_set readfds; tv.tv_sec = 2...
想用select实现非阻塞的程序。只有把超时设为NULL, 也就是select阻塞时, 才能接收到客户端程序的连接。 如果把超时设定为2秒, 就检测不到客户端的连接。这是为什么?
struct timeval tv;
fd_set readfds;
tv.tv_sec = 2;
tv.tv_usec = 0;
FD_ZERO(&readfds);
FD_SET(socket, &readfds);
select(socket, &readfds, NULL, NULL, NULL);
if (FD_ISSET(socket, &readfds))
printf("connection got!n");
else
printf("Timed out.n");
struct timeval tv;
fd_set readfds;
tv.tv_sec = 2;
tv.tv_usec = 0;
FD_ZERO(&readfds);
FD_SET(socket, &readfds);
select(socket, &readfds, NULL, NULL, NULL);
if (FD_ISSET(socket, &readfds))
printf("connection got!n");
else
printf("Timed out.n");
|
我们的服务器程序都用select没有问题。
|
一定要记住,timeout的时间每次都要重新设置,select执行一次后会自动给timeout清零