0

When I catch SIGINT signal in my program, how can I safely clean up resources? In signal handler function it is impossible to call delete operator, because I don't know how to release resource created with new operator.

Any ideas?

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
PDF1001
  • 173
  • 3
  • 13
  • Additional information and a code example here: http://stackoverflow.com/questions/4250013/is-destructor-called-if-sigint-or-sigstp-issued – Sdaz MacSkibbons Jan 27 '11 at 03:48
  • What do you mean it is impossible to call `delete`? – John Zwinck Jan 27 '11 at 03:54
  • 1
    Because SIGINT could happen asynchronously, during a memory management task, and the heap could be inconsistent? What happens when `delete` is called by a signal handler that interrupted a call to `new`? – Mike DeSimone Jan 27 '11 at 03:59

2 Answers2

1

If your application is shutting down, don't worry about memory. The OS is going to throw it all away once you terminate anyway.

The things you need to clean up in your signal handler is stuff that's going to outlive your process otherwise - for example, if a child process you've created needs to exit also, you should tell it to do so.

Anon.
  • 58,739
  • 8
  • 81
  • 86
  • 2
    IIRC, the OS cleans up anything that has a file ID (e.g. files or sockets) as well. It doesn't, however, clean up shared memory, semaphores, and other IPC constructs. – Mike DeSimone Jan 27 '11 at 04:01
  • Right,the os will reclaim the memory,but it just free my memory,not call my destructor which write some information to my log and close log. – PDF1001 Jan 27 '11 at 04:04
1

Generally, you don't want to do much at all in your signal handler except set a boolean flag that will be reacted to by some other part of your program, typically causing some loops to fall through and allowing the familiar approach to orderly shutdown you'd use in cases not involving signals. The reason for using this flag to coordinate the shutdown is that some library functions eschew the compromises required to be safely reentered during async signal handling. Even some thread-safe functions using thread-specific memory may not cope with async reentry. A quick search found some discussion of safe functions at http://book.chinaunix.net/special/ebook/addisonWesley/APUE2/0201433079/ch10lev1sec6.html#ch10lev1sec6.

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
  • In fact i try to set a boolean flag as Tony described.but it seems that all threads stopped in the process and i don't know where to check this flag to let process quit.There is no main entry for my code is a linux library – PDF1001 Jan 27 '11 at 08:19
  • @PDF1001: maybe you should be leaving the signal handling to the applications - it's unusual for a library to take it over, and doesn't scale well (i.e. how well would your library cope if some other library was also trying to handle SIGINT and trigger the application shutdown?). – Tony Delroy Jan 27 '11 at 08:52