Skip to content
TheChatArchiveThe Chat Archive
Qwenqwen3-30b-a3b· Alibaba (Qwen)Hugging Face LMArena Human Preference 140K

How to wait in one thread for a socket to be eventually connected, or listened on

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Qwenqwen-max-2025-01-25’s answer.
  1. User

    How to wait in one thread for a socket to be eventually connected, or listened on

  2. Qwen Assistant

    To wait in one thread for a socket to be connected (as a client) or listened on (as a server), you need to handle these two distinct scenarios separately. Here's how to approach it:


    1. Waiting for a Socket to Be Connected (Client Side)

    For a client socket, you can use poll() or select() to wait until the connection is established after calling connect() in non-blocking mode.

    Steps:

    1. Create the socket in non-blocking mode:
      int fd = socket(AF_INET, SOCK_STREAM, 0);
      fcntl(fd, F_SETFL, O_NONBLOCK); // Set to non-blocking
      
    2. Call connect() on the socket. If the connection is not immediately established, it will return EINPROGRESS.
    3. Poll the socket for POLLOUT (writeable) to detect when the connection is established:
      struct pollfd pfd = { .fd = fd, .events = POLLOUT };
      int ret = poll(&pfd, 1, -1); // Wait indefinitely
      if (ret > 0 && (pfd.revents & POLLOUT)) {
          // Connection is established
      }
      

    Why This Works:

    • The kernel sets POLLOUT when the socket is ready to send data (i.e., the connection is established).
    • If connect() fails, POLLERR will be set, indicating an error.

    2. Waiting for a Socket to Be Listened On (Server Side)

    For a server socket, listen() is a blocking call. Once listen() is called, the socket is in the listening state, and you can use poll() to wait for incoming connections via accept().

    Steps:

    1. Create the socket and bind it to an address:
      int fd = socket(AF_INET, SOCK_STREAM, 0);
      bind(fd, ...);
      listen(fd, 10); // Synchronous call
      
    2. Poll the socket for POLLIN to detect incoming connections:
      struct pollfd pfd = { .fd = fd, .events = POLLIN };
      int ret = poll(&pfd, 1, -1); // Wait indefinitely
      if (ret > 0 && (pfd.revents & POLLIN)) {
          int client_fd = accept(fd, NULL, NULL); // Accept the connection
      }
      

    Why This Works:

    • listen() is a synchronous call, so the thread must explicitly call it.
    • Once the socket is in the listening state, poll() with POLLIN will notify the thread when a new connection arrives.

    3. Handling Both Scenarios in One Thread

    If your application needs to handle either a client or server socket, you must distinguish between the two cases:

    Example Code:

    #include <sys/socket.h>
    #include <sys/poll.h>
    #include <fcntl.h>
    #include <unistd.h>
    #include <stdio.h>
    
    void wait_for_connection(int fd) {
        // For a client socket: wait for POLLOUT after non-blocking connect
        struct pollfd pfd = { .fd = fd, .events = POLLOUT };
        int ret = poll(&pfd, 1, -1);
        if (ret > 0 && (pfd.revents & POLLOUT)) {
            printf("Connection established.\n");
        } else if (pfd.revents & POLLERR) {
            printf("Connection failed.\n");
        }
    }
    
    void wait_for_listen(int fd) {
        // For a server socket: call listen() and then poll for POLLIN
        listen(fd, 10); // Synchronous
        struct pollfd pfd = { .fd = fd, .events = POLLIN };
        int ret = poll(&pfd, 1, -1);
        if (ret > 0 && (pfd.revents & POLLIN)) {
            printf("Incoming connection.\n");
            int client_fd = accept(fd, NULL, NULL);
            // Handle client_fd
        }
    }
    
    int main() {
        int client_fd = socket(AF_INET, SOCK_STREAM, 0);
        fcntl(client_fd, F_SETFL, O_NONBLOCK); // Non-blocking for client
        connect(client_fd, ...); // Initiate connection
        wait_for_connection(client_fd);
    
        int server_fd = socket(AF_INET, SOCK_STREAM, 0);
        bind(server_fd, ...);
        wait_for_listen(server_fd);
    
        return 0;
    }
    

    Key Takeaways

    • Client sockets: Use poll() with POLLOUT after non-blocking connect().
    • Server sockets: Call listen() synchronously, then use poll() with POLLIN to accept connections.
    • No overlap: A socket cannot be both connected and listening at the same time. You must handle these cases separately.

    This approach ensures your thread waits efficiently for the desired state (connected or listening) while adhering to the semantics of TCP sockets.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.