Free memory inside the signal handler

I am writing an API that uses sockets. In the API, I allocate memory for different elements. I want to make sure that I close the sockets and free up memory if there is a signal like Ctrl-C. When examining this, it seems that free () is not on the list of safe functions (signal man 7), so I cannot free memory inside the signal handler. However, I can close the socket. Are there any thoughts on how I can free my memory? Thank you in advance for your time.

+4
source share
4 answers

Alternatively, do not catch the signal and just let the OS handle the cleanup, as it will during the cleanup process. You do not release any resources that are not directly linked to the process, so there is no particular need to manually release them.

+5
source

One method (others exist too):

  • Ask your program to start the main processing cycle.
  • Ask your main processing loop to check the flag so that it can "continue to work."
  • Ask your signal handler to simply set the "keep running" flag to false, but not to terminate the program otherwise.
  • Before exiting your main processing, clear the memory.

This has the advantage of placing both distribution and allocation in blocks of code that are called with a known sequence. This can be a find when working with networks of interconnected objects, and between two processing flows there should not be race conditions that try to spoil the same object.

+4
source

Do not get free in the handler. Instead, tell your program that something needs to be freed. Then find this in your program so that you can free yourself from the main context, not the signal context.

+2
source

Are you writing a library or application? If you are writing a library, you do not have a business installing signal handlers that run counter to the calling application. This is a business application to process such signals, if it wants, and then make the appropriate cleanup calls to your library (outside the context of the signal handler).

Of course, even if you are writing an application, there is no reason to process SIGINT to close sockets and free memory. The only reasons for signal processing: if you do not want to stop working, or if you have unsaved data or a general condition (for example, material in shared memory or the file system) that you need to clear before completion. Freeing memory or closing file descriptors that are used exclusively by your own process are not tasks that you must complete when you exit.

+2
source

Source: https://habr.com/ru/post/1393218/


All Articles