Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit a blocking accept() call in Windows?

I have a blocking accept() call in a thread that is waiting for connection requests. When the application is about to close, I want to signal the thread that is waiting on accept() to exit gracefully. I have found in the documentation for Winsock that I can set a timeout value for send() and recv(), but I can't do that for accept().

I have read that I can make the socket non-blocking and use select(), and pass a timeout value for select(), but I am looking for a solution for blocking sockets.

like image 703
user6745975 Avatar asked Aug 23 '16 03:08

user6745975


1 Answers

I have read that I can make the socket non-blocking and use select(), and pass a timeout value for select(), but I am looking for a solution for blocking sockets.

You can do this on blocking socket:

sock = socket(...);
bind(sock, ...);
listen(sock, ...);

while (program_running()) 
{
    timeval timeout = {1, 0};
    fd_set fds;
    FD_ZERO(&fds);
    FD_SET(sock, &fds);

    select(sock+1, &fds, NULL, NULL, &timeout);

    if (FD_ISSET(sock, &fds))
    {
        client = accept(sock, ...);

        // do things with client
    }

From MSDN accept function documentation:

The parameter readfds identifies the sockets that are to be checked for readability. If the socket is currently in the listen state, it will be marked as readable if an incoming connection request has been received such that an accept is guaranteed to complete without blocking.

like image 92
Mathieu Avatar answered Oct 22 '22 03:10

Mathieu