views:

132

answers:

1

Hello

I have the following code implemented on C++(Linux) to check on my listening socket and stdin using select. select however keeps returning -1 no matter what I try to do! What's wrong with that code :s I will appreciate any help. Thanks

highsock = m_sock; //listening socket

memset((char *) &connectlist, 0, sizeof(connectlist));
memset((char *) &socks, 0, sizeof(socks));

int readsocks;
struct timeval timeout;
timeout.tv_sec = 60;
timeout.tv_usec = 0;

while (1) {
    updateSelectList();
    //cout << "highest sock: " << highsock << endl;
    tempreadset = readset;
    readsocks = select(highsock+1, &tempreadset, NULL, NULL, &timeout);
    //cout << "# ready: " << readsocks << endl;
    if (readsocks < 0) {
        if (errno == EINTR)
            continue;
        cout << "select error" << endl;
    }
    if (readsocks > 0) {
        readFromSocks();
    }
}

void readFromSocks() {
    if (FD_ISSET(STDIN, &readset)) {
    ...
    } else if (FD_ISSET(m_sock, &readset)) {
    ...
    }
}

void updateSelectList() {
    FD_ZERO(&readset);

    FD_SET(STDIN, &readset);
    FD_SET(m_sock, &readset);

    for (int i=0; i<MAXCONNECTIONS; i++) {
        if (connectlist[i] != 0) {
            FD_SET(connectlist[i], &readset);
            if (connectlist[i] > highsock)
                highsock = connectlist[i];
        }
    }

    highsock = max(max(m_sock, STDIN), highsock);
}
A: 

Some things to change, which might help:

1) Set highsock to -1 at the top of each while loop (otherwise it may be too high, reflecting a socket that used to be art of your socket set but is now invalid)

2) Set the values in the timeval struct at the start of each loop, instead of once before the loop starts. (Also, you might want to pass in NULL as the timeval argument just to see if that makes the problem go away... I've seen select() fail when passed a timeval that it didn't like)

Jeremy Friesner
I tried them both nothing happens. Here is the output:highest sock: 3Select failure: select returned a negative value!
Aleyna
I update highsock in the updateSelectList and remove any socket from connectionlist array when it is closed so setting highsock to -1 has no effect.
Aleyna
Except that according to the posted code, when you update highsock in updateSelectList() you are updating it to be the maximum of the other sockets and itself... so old large values of highsock will be preserved even when they are no longer appropriate.
Jeremy Friesner
Aleyna