Does my program need to be able to handle SIGINT?

Viewed 149

Should I worry about handling the event that user passes SIGINT in the middle of using my program?

The program in question deals with heap allocations and frees, so I am worried that such a situation would cause a memory leak. When I pass SIGINT in the middle of using the program, Valgrind states:

==30173== Process terminating with default action of signal 2 (SIGINT)
==30173==    at 0x4ACC142: read (read.c:26)
==30173==    by 0x4A4ED1E: _IO_file_underflow@@GLIBC_2.2.5 (fileops.c:517)
==30173==    by 0x4A41897: getdelim (iogetdelim.c:73)
==30173==    by 0x109566: main (main.c:55)
==30173== 
==30173== HEAP SUMMARY:
==30173==     in use at exit: 1,000 bytes in 1 blocks
==30173==   total heap usage: 3 allocs, 2 frees, 3,048 bytes allocated
==30173== 
==30173== LEAK SUMMARY:
==30173==    definitely lost: 0 bytes in 0 blocks
==30173==    indirectly lost: 0 bytes in 0 blocks
==30173==      possibly lost: 0 bytes in 0 blocks
==30173==    still reachable: 1,000 bytes in 1 blocks
==30173==         suppressed: 0 bytes in 0 blocks
==30173== Rerun with --leak-check=full to see details of leaked memory
==30173== 
==30173== For lists of detected and suppressed errors, rerun with: -s
==30173== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
1 Answers

The answer is OS-dependent. Most modern operating systems will clean up memory allocated by your process once it is killed (Windows, Linux, *nix in general, and more). This is usually just part of the OS memory isolation and protection system, where each process gets its own virtual memory mapping and the physical pages corresponding to that mapping are allocated / freed by way of reference counting (a killed / exited process will decrement the reference counts to its mapped physical pages and free them if they reach zero).

If you plan on running your process on obscure embedded systems with no such guarantees with respect to memory management, then perhaps you might need to worry about such a thing. Otherwise, if memory management is your only concern, then it's a non-issue.

If you want to account for other things which should happen on exit (e.g. saving state), then you will certainly need to trap SIGINT, likely along with other signals as well.

Related