Search code examples
clinuxkill

Linux C catching kill signal for graceful termination


I have a process using sockets, database connections and the likes. It is basically a server process relaying between sensor data and a web interface, and as such it is important to ensure the application, if killed, terminates gracefully.

How do I handle unexpected exceptions such as segfaults (at least for debugging) as well as kill signals so that I can close any connections and stop any threads running so that the process does not leave a mess of anything it is using?


Solution

  • You install signal handlers to catch signals -- however in 99% of cases you just want to exit and let the Linux OS take care of the cleanup -- it will happily close all files, sockets, free memory and shutdown threads.

    So unless there is anything specifically you want to do, like sending a message on the sockets, then you should just exit from the process and not try to catch the signal.