3

I developed a server with C code.

I used the accept() function to keep my server listening on a giving socket.

My server is launched in a thread.

Now in other thread and for some condition I want to stop the accept() blocking and then close the related socket.

How I can do that? Could shutdown() do that?

alk
  • 69,737
  • 10
  • 105
  • 255
MOHAMED
  • 41,599
  • 58
  • 163
  • 268
  • I'm not positive but I suspect you could simply `close()` the socket that `accept()` is on. Perhaps `shutdown()` does that. What happened when you tried? – mah Mar 02 '16 at 18:07
  • Does this answer your question? [Boost::asio - how to interrupt a blocked tcp server thread?](https://stackoverflow.com/questions/11191028/boostasio-how-to-interrupt-a-blocked-tcp-server-thread) – Alex Jun 13 '20 at 09:32

3 Answers3

4

[This does not work on Windows]

  • Use sigaction() to install a signal handler for let's say SIGUSR1 doing nothing, but having the SA_RESTART option unset (also see section "Interruption of system calls and library functions by signal handlers" on this man-page).

  • Then send the blocking process a SIGUSR1 signal.

accept() will then return -1 and set errno to EINTR.

alk
  • 69,737
  • 10
  • 105
  • 255
3

Classically, closing the socket from another thread causes the accept() call to return with an error. I have been told that this does not work on some releases of Linux, but have seen no evidence of that myself - every time, on Windows/Linux, the accept() returns with an error/exception.

The other common solution is to check some 'shutdown' atomic boolean after every accept() return. When you want to stop it, set the boolean and perform a connect() on the localhost stack, so causing the accept() to return in the 'normal' way.

Martin James
  • 24,453
  • 3
  • 36
  • 60
  • Should be slightly corrected: instead of close() do shutdown() for portable solution. More details here https://stackoverflow.com/a/62356967/70405 . Don't mind the boost involvement, solution is at socket API level. – Alex Jun 13 '20 at 09:32
2

I was having trouble with accept not terminating after I only called close on the socket under Linux Mint 18.3. I solved it by also calling shutdown(socket_fd, SHUT_RD); before the close

mah already mentioned it, but I wanted to highlight this, because this is the first SO result in a google search for "socket stop accept".

Algoman
  • 1,905
  • 16
  • 16