Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

c - Select always return 1 after create socket and FD_SET in linux

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The first problem is the FD_SET. The first parameter should be the file descriptor of the socket:

FD_SET( sockfd, &rfds );

There is also a problem in the select call. The first parameter must be greater than the max descriptor. From the man page for select:

(Example: If you have set two file descriptors 4 and 17, nfds should not be 2,
but rather 17 + 1, i.e. 18.)

So the select call should be:

select( sockfd+1, &rfds, NULL, NULL, &tv );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...