Search code examples
cclient-serversignal-handling

Custom Signal handler in C. for (Alt+F4)


In C programming, ctrl+c is seen as a signal interrupt and it shuts down the program, which I would call a graceful shutdown. But in some unforeseen circumstances, can the server shutdown be handled like the ctrl+c exit?

History: I have 2 servers, A and B. A can be considered as a central server which acts like a repository for many servers that can register to it. Now, B is another server on the same network, when it runs, it registers with A. Next, when i press ctrl+c on the terminal instance of serverB, the server shuts down and also smoothly deregisters itself from the central server (A).

However, if I just close the terminal of B, the server A assumes that the serverB is still active, but in reality it has terminated.

So to handle this scenario, is there any way to consider alt+f4 as a signal interrupt, so that i replicate the scenario of a smooth exit?

Any guidance would be useful.

Thanks in advance


Solution

  • As guys told before me you can register signal handler function for SIGHUP signal with call

    signal(SIGINT,sig_handler)
    

    Also If I'm not wrong if you use gcc of course you might use function attribute

    __attribute__((destructor[(priority)]))
    

    If you implement something to smoothly disconnect from desired server it will work for any type of termination of your program (except SEGFAULT).

    But still signal handler will be best solution