Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

freeing memory inside a signal handler

I am writing an API that uses sockets. In the API, I allocate memory for various items. I want to make sure I close the sockets and free the memory in case there is a signal such as Ctrl-C. In researching this, it appears free() is not on the safe function list (man 7 signal) thus, I can't free the memory inside a signal handler. I can close the socket just fine though. Does any have any thoughts on how I can free the memory? Thank you in advance for your time.

like image 639
Mike Avatar asked Jan 26 '12 17:01

Mike


People also ask

What are you allowed to do in a signal handler?

Signal handlers can be specified for all but two signals (SIGKILL and SIGSTOP cannot be caught, blocked or ignored). If the signal reports an error within the program (and the signal is not asynchronous), the signal handler can terminate by calling abort() , exit() , or longjmp() .

Can a signal handler be interrupted?

Signal handlers can be interrupted by signals, including their own. If a signal is not reset before its handler is called, the handler can interrupt its own execution. A handler that always successfully executes its code despite interrupting itself or being interrupted is async-signal-safe.

What happens when a signal handler returns?

If a signal handler returns in such a situation, the program is abnormally terminated. The call to signal establishes signal handling for only one occurrence of a signal. Before the signal-handling function is called, the library resets the signal so that the default action is performed if the same signal occurs again.

Do signal handlers run concurrently?

Signal handlers run concurrently with main program (in same process).


2 Answers

Alternatively, don't catch the signal and just let the OS handle the cleanup as it's going to do during process cleanup anyway. You're not releasing any resources that aren't tied directly to the process, so there's no particular need to manually release them.

like image 78
jamessan Avatar answered Sep 27 '22 22:09

jamessan


One technique (others exist too):

  1. Have your program run a main processing loop.
  2. Have your main processing loop check a flag to see if it should "keep running".
  3. Have your signal handler simply set the "keep running" flag to false, but not otherwise terminate the program.
  4. Have your main processing loop do the memory cleanup prior to exiting.

This has the benefit of placing both the allocation and de-allocation in blocks of code which are called with a known sequence. Doing so can be a godsend when dealing with webs of interrelated objects, and there is not going to be race condition between two processing flows trying to mess with the same object.

like image 40
Edwin Buck Avatar answered Sep 27 '22 21:09

Edwin Buck