socket programming with select

1.1k views Asked by At

I have two nodes communicating with a socket. Each node has a read thread and a write thread to communicate with the other. Given below is the code for the read thread. The communication works fine between the two nodes with that code. But I am trying to add a select function in this thread and that is giving me problems (the code for select is in the comments. I just uncomment it to add the functionality). The problem is one node does not receive messages and only does the timeout. The other node gets the messages from the other node but never timesout. That problem is not there (both nodes send and receive messages) without the select (keeping the comments /* */).

Can anyone point out what the problem might be? Thanks.

void *Read_Thread(void *arg_passed)
{   
    int numbytes;
    unsigned char *buf;
    buf = (unsigned char *)malloc(MAXDATASIZE);

    /*
    fd_set master;
    int fdmax;
    FD_ZERO(&master);
    */

    struct RWThread_args_template *my_args = (struct RWThread_args_template *)arg_passed;

    /*
    FD_SET(my_args->new_fd, &master);
    struct timeval tv;
    tv.tv_sec = 2;
    tv.tv_usec = 0;
    int s_rv = 0;
    fdmax = my_args->new_fd;
    */

    while(1)
    {
        /*
        s_rv = -1;
        if((s_rv = select(fdmax+1, &master, NULL, NULL, &tv)) == -1)
        {
            perror("select");
            exit(1);
        }
        if(s_rv == 0)
        {
            printf("Read: Timed out\n");
            continue;
        }
        else
        {
            printf("Read: Received msg\n");
        }
        */
        if( (numbytes = recv(my_args->new_fd, buf, MAXDATASIZE-1, 0)) == -1 )
        {
            perror("recv");
            exit(1);
        }
        buf[numbytes] = '\0';

        printf("Read: received '%s'\n", buf);
    }
    pthread_exit(NULL);
}
1

There are 1 answers

0
caf On BEST ANSWER

You must set up master and tv before each call to select(), within the loop. They are both modified by the select() call.

In particular, if select() returned 0, then master will now be empty.