Today I was creating a sample code socket in Linux (Debian). But it run incorrectly, after FD_ZERO
and FD_SET
. select
will return 1 before time out (my expectation is that select would return 0 ) but i had not taken action with the socket. Here is my code. Could someone help me?
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
int
main(void)
{
fd_set rfds;
struct timeval tv;
int sockfd, retval;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
/* Watch sockfd to see when it has input. */
FD_ZERO(&rfds);
FD_SET(sockfd, &rfds);
/* Wait up to five seconds. */
tv.tv_sec = 5;
tv.tv_usec = 0;
retval = select(FD_SETSIZE, &rfds, NULL, NULL, &tv);
/* Don't rely on the value of tv now! */
if (retval == -1)
perror("select()");
else if (retval)
printf("Data is available now.
");
/* FD_ISSET(sockfd, &rfds) will be true. */
else
printf("No data within five seconds.
");
exit(EXIT_SUCCESS);
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…