/* Purpose:  show that any of several signals can be usefully be 
		intercepted

   Details:  the program loops for 20,000,000 iterations and 
	     displays its progress every 1,000,000 iterations.
	     If the user types control-c, control-\, or sends
	     a terminate signal, the program confirms
	     that termination is appropriate and then does so.
									*/ 

#include <iostream>
using namespace std;

#include <stdlib.h>
#include <unistd.h>
#include <signal.h>

#define LINELEN_MAX 1024

extern "C" void quit(int sig);	/* forward declaration of function */

int main(void)
{
	int i;

	signal(SIGINT,  quit);    
	signal(SIGTERM, quit);    
	signal(SIGQUIT, quit);    

	/* do nothing useful for 20,000,000 iterations */ 
	for (i = 1; i <= 20000000; i++)
	{
		if (i % 1000000 == 0)
		{
			cout << "i = " << i << endl;
		}
	}
	exit(EXIT_SUCCESS);
}

void quit(int sig) {    
	char response[LINELEN_MAX];
	//signal(SIGINT,  quit);    
	//signal(SIGTERM, quit);    
	//signal(SIGQUIT, quit);    
	signal(sig, quit);
	cerr << "Are you sure that you want to quit? ";    
	cerr.flush();
	cin >> response;
	if (response[0] == 'Y' || response[0] == 'y')
	{
		exit(EXIT_SUCCESS);	/* or kill(getpid(), SIGKILL) */    
	}
}
