Bortds
Bortds

Reputation: 11

Handling Ctrl-C in a Linux TCP/IP Server written in C

I'm currently working on a Linux TCP/IP server. The server program is running in C. I'm currently testing it, but each time I exit it with Ctrl-c, the port it's using is not released, neither is the database it's been writing to unlocked. How does one define a subroutine that will exit when a Ctrl+C signal is received?

Upvotes: 1

Views: 2486

Answers (3)

jtdubs
jtdubs

Reputation: 13983

Two options:

  1. Add a cleanup routine with: int atexit(void (*function)(void));
  2. Hook Ctrl+C with: sighandler_t signal(int signum, sighandler_t handler);

As R pointed out, sigaction is more portable than signal, but perhaps less idiomatic for Linux.

Warning: atexit routines won't run if your program is killed with SIGKILL (Ctrl+/) or any other unhandled signal is received.

Upvotes: 1

prabhakaran
prabhakaran

Reputation: 5274

@Bortds Generally the port won't be released immediately, you have to wait to for some time. I found this from a server project I worked.

Upvotes: 1

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215457

Lookup setsockopt and SO_REUSEADDR. This option must have been set on the old original server process's socket or the new one will not be able to bind the port until the TIME_WAIT period expires.

Upvotes: 1

Related Questions