I wrote a server/client program. And use select
check socket. But when client close socket(tcp status in server will get in close_wait
), select always return 1 and errno is 0.
Why select
return 1? Tcp socket have nothing to read now!
server:
int sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(6999);
socklen_t socklen = sizeof(struct sockaddr_in);
bind(sock, (struct sockaddr *)&addr, socklen);
listen(sock, 0);
int clisock;
clisock = accept(sock, NULL, NULL);
fd_set backset, rcvset;
struct timeval timeout;
timeout.tv_sec = 3;
int maxfd = clisock+1;
FD_SET(clisock, &rcvset);
backset = rcvset;
int ret;
while(1) {
rcvset = backset;
timeout.tv_sec = 3;
ret = select(maxfd, &rcvset, NULL, NULL, &timeout);
if(ret <= 0)
continue;
sleep(1);
printf("ret:%d, %s\n",
ret, strerror(errno));
}
client:
int sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
addr.sin_port = htons(6999);
socklen_t socklen = sizeof(struct sockaddr_in);
connect(sock, (struct sockaddr *)&addr, socklen);
sleep(3);
close(sock);
sleep(100);
output:
./server
ret:1, Success
ret:1, Success
ret:1, Success
read
returning0
. That is the indication that the remote end-point has been closed,read
returning0
. – Some programmer dudeerrno
, don't check it unless there actually is an error, and always check it directly after the erroneous function call (i.e. ifselect
fail you have to checkerrno
directly afterselect
). Think about what would happen ifsleep
failed? Thenerrno
would contain the error from thesleep
function. – Some programmer dudeselect
modifies the sets, so if you have multiple descriptors in the sets you pass toselect
, you have to clear the set and add all descriptors again. – Some programmer dudeerrno
if there is no error is undefined, don't check it unless there is an error. – Some programmer dude