How to wait in one thread for a socket to be eventually connected, or listened on
- User
How to wait in one thread for a socket to be eventually connected, or listened on
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()orselect()to wait until the connection is established after callingconnect()in non-blocking mode.Steps:
- 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 - Call
connect()on the socket. If the connection is not immediately established, it will returnEINPROGRESS. - 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
POLLOUTwhen the socket is ready to send data (i.e., the connection is established). - If
connect()fails,POLLERRwill 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. Oncelisten()is called, the socket is in the listening state, and you can usepoll()to wait for incoming connections viaaccept().Steps:
- Create the socket and bind it to an address:
int fd = socket(AF_INET, SOCK_STREAM, 0); bind(fd, ...); listen(fd, 10); // Synchronous call - Poll the socket for
POLLINto 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()withPOLLINwill 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()withPOLLOUTafter non-blockingconnect(). - Server sockets: Call
listen()synchronously, then usepoll()withPOLLINto 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.
- Create the socket in non-blocking mode:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.