// SIGNAL.C -- Install a CTRL-C handler with signal()

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <conio.h>
#include <ctype.h>
#include <dos.h>
#include <pldos32.h>

void __cdecl CCHandler(int sig);

int main()
{
	UCHAR	ch;

//
// Test 1: Install our CTRL-C handler, and prompt user to type CTRL-C
//
	if (signal(SIGINT, CCHandler) == SIG_ERR)
	{
		printf("Couldn't install CTRL-C handler\n");
		return 1;
	}
	do 
	{
		printf("\nType CTRL-C to invoke handler, 'N' for next test: ");
		_dos_char_ine(&ch);
	}
	while (_toupper(ch) != 'N');

//
// Test 2:  Ignore CTRL-C, and prompt user
//
	if (signal(SIGINT, SIG_IGN) == SIG_ERR)
	{
		printf("Couldn't ignore CTRL-C\n");
		return 1;
	}
	do
	{
		printf("\nCTRL-C should be ignored, type 'N' for next test: ");
		_dos_char_ine(&ch);
	}
	while (_toupper(ch) != 'N');

//
// Test 3:  System-default response is to kill program.
//
	if (signal(SIGINT, SIG_DFL) == SIG_ERR)
	{
		printf("Couldn't set default response for CTRL-C\n");
		return 1;
	}
	do
	{
		printf("\nType CTRL-C to kill program, 'N' for normal exit: ");
		_dos_char_ine(&ch);
	}
	while (_toupper(ch) != 'N');
	printf("\n");

	return 0;
}

//
// CCHandler -- prompts user to kill program or continue
//
// C run-time library I/O routines are not safe to use inside a signal
// handler, so call DOS directly for I/O.
//
void __cdecl CCHandler(int sig)
{
	UCHAR	ch;

//
// Disallow a second CTRL-C while we're handling this one
//
	signal(SIGINT, SIG_IGN);

//
// Prompt user to continue or die
//
	_dos_str_out("\r\nCTRL-C typed!!!!  Enter 'K' to kill program: $");
	_dos_char_ine(&ch);
	if (toupper(ch) == 'K')
		abort();

//
// Re-install our handler, re-prompt user, and continue program
//
	signal(SIGINT, CCHandler);
	_dos_str_out("\r\nType CTRL-C to invoke handler, \
'N' for next test: $");
	return;
}
