user110357
user110357

Reputation: 1

Closing a server socket in C linux

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.

Upvotes: 0

Views: 4346

Answers (2)

alk
alk

Reputation: 70883

  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.

Upvotes: 0

Greg Hewgill
Greg Hewgill

Reputation: 992707

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().

Upvotes: 1

Related Questions