0

I have a server program which looks like this

{
    socket();
    bind();
    listen();

    while(1)
    {
        accept();
        recv();
        send();
        close();
    }

    close();
}

Let's say the server is running, listening at the specified port. How can I close it by pressing a keypad? I mean a proper closure, not by Ctrl+C.

James M
  • 18,506
  • 3
  • 48
  • 56
user110357
  • 1
  • 1
  • 1
  • As @guido said you can [poll the socket for connections](http://stackoverflow.com/questions/14045064/how-to-accept-socket-with-timeout). – Basilevs Dec 03 '13 at 16:49

2 Answers2

1

When you close() a socket that is blocking in accept(), then the accept() call will return immediately with -1.

If your program is single threaded like you show, then you can't do the above. You would need to introduce at least one additional thread to actually do the close().

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
0
  1. Have the program install a signal handler (for SIGUSR1 for example) doing nothing.

  2. Use setsockopt() to unset the option SA_RESTART for the sockets in use.

  3. Make the code issuing socket related system calls aware that they might return with -1 and errno set to EINTR.

  4. Run the program.

  5. Send it a signal for which the program has a handler installed (in 1.) from the outside (by for example using the kill <pid> -USR1 command).

  6. Detect the reception of a signal (see 3.) and react, for example by close()ing the socket in question.

alk
  • 69,737
  • 10
  • 105
  • 255