Program 1 loops forever, calling the self-explanatory Beep function every 5 seconds. The user can terminate the program with a Ctrl-C or by closing the console. The handler routine will put out a message, wait 10 seconds, and, it would appear, return TRUE, terminating the program. The main program, however, detects the exitFlag flag and stops the process. This illustrates the concurrent operation of the handler routine; note that the timing of the signal determines the extent of the signal handler’s output.
Program 1. Ctrlc: Signal Handling Program
#include "Everything.h"static BOOL WINAPI Handler(DWORD cntrlEvent);static BOOL exitFlag = FALSE;int _tmain(int argc, LPTSTR argv[])/* Beep periodically until signaled to stop. */{ /* Add an event handler. */ SetConsoleCtrlHandler(Handler, TRUE); while (!exitFlag) { Sleep(5000); /* Beep every 5 seconds. */ Beep(1000 /* Frequency. */, 250 /* Duration. */); } _tprintf(_T("Stopping the program as requested.\n")); return 0;}BOOL WINAPI Handler(DWORD cntrlEvent){ exitFlag = TRUE; switch (cntrlEvent) { /* Timing determines if you see the second handler message. */ case CTRL_C_EVENT: _tprintf(_T("Ctrl-C. Leaving in <= 5 seconds.\n")); exitFlag = TRUE; Sleep(4000); /* Decrease to get a different effect */ _tprintf(_T("Leaving handler in 1 second or less.\n")); return TRUE; /* TRUE indicates the signal was handled. */ case CTRL_CLOSE_EVENT: _tprintf(_T("Close event. Leaving in <= 5 seconds.\n")); exitFlag = TRUE; Sleep(4000); /* Decrease to get a different effect */ _tprintf(_T("Leaving handler in <= 1 second.\n")); return TRUE; /* Try returning FALSE. Any difference? */ default: _tprintf(_T("Event: %d. Leaving in <= 5 seconds.\n"), cntrlEvent); exitFlag = TRUE; Sleep(4000); /* Decrease to get a different effect */ _tprintf(_T("Leaving handler in <= 1 second.\n")); return TRUE; /* TRUE indicates the signal was handled. */ }} |
Note the use of WINAPI; this macro is for user functions passed as arguments to Windows functions to assure the proper calling conventions. It is defined in the Platform SDK header file windef.h.
There’s very little to show with this program, as we can’t show the sound effects. Nonetheless, Run 4-5 shows the command window where I typed Ctrl-C after about 11 seconds.