Skip to content
Advertisement

Control doesn’t move next to the select function

i am trying to implement a TCP server that accepts multiple client nodes. However, the control is just stuck at select() and not moving beyond that. This is my code:

#include <iostream>
#include <string>
#include <sys/types.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>

int main(){
    int server_socket = socket(AF_INET, SOCK_STREAM, 0);

    sockaddr_in hint;
    hint.sin_family = AF_INET;
    hint.sin_port = htons(2987);
    inet_pton(AF_INET, "0.0.0.0", &hint.sin_addr);

    bind(server_socket, (sockaddr*)&hint, sizeof(hint));
    listen(server_socket, SOMAXCONN);

    fd_set master;
    FD_ZERO(&master);
    FD_SET(server_socket, &master);

    int client_socket;
    sockaddr_in client_addr;
    socklen_t client_len = sizeof(client_addr);

    while(true){
        fd_set copy = master;
        int socket_count = select(0, &copy, nullptr, nullptr, nullptr);

        cout << "Reached here!" << endl;

        for(int i=0; i<socket_count; i++){
            if(FD_ISSET(i, &copy)){
                if(i == server_socket){
                    client_socket = accept(server_socket, (sockaddr *) &client_addr, &client_len);
                }else{
                    // Message
                }
            }
        }
    }
}

However, the control never moves beyond the select statement. It just remain there even after i open a connection to the server with telnet:

$ telnet 127.0.0.1 2987

Why it stuck there and how do i get the client socket with this?

Advertisement

Answer

Here is the manual of select.

The first parameter should not be zero, but be the highest file-descriptor that select should manage plus 1. In your case it’s:

int socket_count = select(server_socket + 1, &copy, nullptr, nullptr, nullptr);
Advertisement