Maanu
Maanu

Reputation: 5203

Can accept() return without getting a connection?

I have a blocking TCP socket, which is blocking at the accept() call. Is it possible to make the accept() call return (other than by getting a connection from a client)? This is for closing the socket as part of system shutdown and exiting the thread which is accepting the connections.

Upvotes: 1

Views: 587

Answers (3)

Maciej Szpakowski
Maciej Szpakowski

Reputation: 581

In windows, WSA will cancel accept (accept will return INVALID_SOCKET) if you close accepting connection (call closesocket()).

Upvotes: 0

blaze
blaze

Reputation: 4364

1) In a single threaded program you can use a signal from another process. Make sure you do NOT pass the SA_RESTART flag when installing signal handler.

2) If you need to stop accept() from another thread of the same process, create a socketpair or pipe and block on select() on your socket and this pipe. When you need to unblock, write something to the pipe.

3) Or just use select() with some small timeout (1 second) and poll the exit flag each time it returns.

Upvotes: 4

Liv
Liv

Reputation: 6124

Use SOCK_NONBLOCK in the flags parameter : http://www.linuxhowtos.org/manpages/2/accept.htm

Upvotes: 2

Related Questions