开发者

select always returns -1 while trying to read from socket and stdin

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);
}


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜