我的程序是否需要能够处理 SIGINT?

Does my program need to be able to handle SIGINT?

我是否应该担心处理用户在使用我的程序过程中传递 SIGINT 的事件?

问题程序涉及堆分配和释放,所以我担心这种情况会导致内存泄漏。当我在使用该程序的过程中传递 SIGINT 时,Valgrind 声明:

==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)

答案是 OS 相关的。大多数现代操作系统会在进程终止后清理进程分配的内存(Windows、Linux、*nix 等)。这通常只是 OS 内存隔离和保护系统的一部分,其中每个进程都有自己的虚拟内存映射,并且通过引用计数分配/释放对应于该映射的物理页面(一个被杀死/退出的进程将减少对其映射的物理页面的引用计数,并在它们达到零时释放它们。

如果您计划 运行 在晦涩难懂的嵌入式系统上处理您的进程,并且在内存管理方面没有此类保证,那么您可能需要担心这样的事情。否则,如果内存管理是您唯一关心的问题,那么这不是问题。

如果您想考虑退出时应该发生的其他事情(例如保存状态),那么您肯定需要捕获 SIGINT,可能还需要捕获其他信号。