Search code examples
csocketsposix-select

event based socket programming in C


when the call to select statement returns , we check for the active file descriptors to process the multiple client's request.

select(maxfd+1, &readfds, NULL, NULL, NULL);

That , is select command monitors the file descriptors in the readfds set. My Question is , while at the time of processing the client's request , more new connections arrives at the listening socket , how would the program capture those new connections ?


Solution

  • You learn about that if you monitor the server socket in the readfd set of select(). Select indicating a server socket as readable, means there's a connection waiting, so you can accept() it.

    ...
    FD_SET(server_sock, &readfds);
    
    select(maxfd + 1,&readfds,NULL,NULL,NULL); 
    if(FD_ISSET(server_sock, &readfds)) {
        int new_client = accept(server_socket, ... );
        //add the new client to descriptors to monitor, etc..
    

    (Note that the OS does the initial TCP handshake and establishes a connection, accept() just makes the connection available for your program)