1

I want to execute a housekeeping function when a C program exits. I know about atexit() which can help register a function for normal exit but will not work for signals like SIGINT or SIGQUIT. I don't want to register signal handlers for all such signals whose default behavior is to terminate the program. I just want to register a function which will get executed before a program terminates no matter what the reason is. How can I do this in C?

Kara
  • 6,115
  • 16
  • 50
  • 57
Bruce
  • 33,927
  • 76
  • 174
  • 262
  • 2
    I think No choice for this. [**A related question**](http://stackoverflow.com/questions/12437648/uninterruptable-process-in-windowsor-linux) I posted, may be helpful to you – Grijesh Chauhan Dec 27 '12 at 17:14
  • Which platform for you are working, if window then Hooks **may be** useful to use upto some extend. – Grijesh Chauhan Dec 27 '12 at 17:25
  • What about the approach mentioned by the last paragraph of this answer: http://stackoverflow.com/a/12741496/694576 ? – alk Dec 27 '12 at 17:44
  • Kernel modules are not a good solution - they are far too sensitive to variations in kernel version, and a lot of people, including myself wouldn't install an extra kernel module unless there was a REALLY good reason for it. – Mats Petersson Dec 27 '12 at 23:40
  • I have this problem too. Wow. This identical problem. If only this question had better answers –  Oct 14 '19 at 20:09

3 Answers3

2

Can you run your c program as a child process ? you could use any exec family function for that matter.

If your child process gets terminated normally or abnormally then there are much better options to query the exit status of the child from parent process.

According to that you should be able to invoke your function in parent.

Icarus3
  • 2,310
  • 14
  • 22
  • 1
    +1 from me too... But of course, that does assume that the information needed to complete the cleanup is not part of the executable that was being shut down. – Mats Petersson Dec 27 '12 at 23:38
0

Well I am not a C/C++ developer but have a look at this question that may help you. Shutdown Hook c++. There is a very fine way in Java though but in C I don't think there is a dedicated function to fullfill the purpose.

Community
  • 1
  • 1
ktk
  • 297
  • 4
  • 13
0

If you know already what type of signal you will be receiving you can write a signal handler in c.

for Linux check this answer: Ctrl + C interrupt event handling in Linux

some extra references: https://www.gnu.org/software/libc/manual/html_node/Signal-Handling.html#:~:text=24%20Signal%20Handling,disconnection%20of%20a%20phone%20line.

For windows check the following link: C++: Continue execution after SIGINT