Q: How can I trap or ignore keyboard interrupts like control-C?
A: The basic step is to call signal, either as
#include <signal.h> signal(SIGINT, SIG_IGN);to ignore the interrupt signal, or as
extern void func(int); signal(SIGINT, func);to cause control to transfer to function func on receipt of an interrupt signal. [footnote]
On a multi-tasking system such as Unix, it's best to use a slightly more involved technique:
extern void func(int); if(signal(SIGINT, SIG_IGN) != SIG_IGN) signal(SIGINT, func);The test and extra call ensure that a keyboard interrupt typed in the foreground won't inadvertently interrupt a program running in the background (and it doesn't hurt to code calls to signal this way on any system). [footnote]
On some systems, keyboard interrupt handling is also a function of the mode of the terminal-input subsystem; see question 19.1. On some systems, checking for keyboard interrupts is only performed when the program is reading input, and keyboard interrupt handling may therefore depend on which input routines are being called (and whether any input routines are active at all). On MS-DOS systems, setcbrk or ctrlbrk functions may also be involved.
References:
ISO Secs. 7.7,7.7.1
H&S Sec. 19.6 pp. 411-3
PCS Sec. 12 pp. 210-2
POSIX Secs. 3.3.1,3.3.4