Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Normally you can interrupt the execution of a program by typing^C or^\\ from the

ID: 3815854 • Letter: N

Question

Normally you can interrupt the execution of a program by typing^C or^ from the keyboard. Write a program, in C (not C + +), which is hard to kill. Your program should not be killed until two^C's and two^'s have been typed from the keyboard (in any order). You can imagine that your program has 4 lives, and each of the first two^C's and^'s reduces the number of lives by 1. Your program should keep displaying (with 1 second delay, which can be achieved by the function call sleep(l)) one of the following messages, depending on how many lives left;| 4 lives: Still going strong! 3 lives: Hit, still going! 2 lives: Wounded, still going! 1 live: Dying, still going! 0 live: Dead!

Explanation / Answer

/*I don't have *nix on my computer so this has been tested on windows. As windows does not support the SIGQUIT signal (for CTRL+/)
I can't show you the output. However the below code should work on *nix*/
#include <stdio.h>
#include <stdlib.h>
#include<signal.h>
#include<unistd.h>
//#include<windows.h>

/* counts for the number of times Ctrl+C and Ctrl+ are pressed*/
int CtrlC_Count=0;
int CtrlSlash_Count=0;
/*number of lives remaining*/
int lives=4;

void CtrlSlashHandler(int s)
{
if(CtrlSlash_Count<2) /*we only want to capture the first two times that Ctrl+ is pressed*/
{
CtrlSlash_Count++; //increment the CTRL+ counter
lives--; //decrement the lives counter
}
if(lives==0) //if out of lives, return for exiting the program
{
return;
}
signal(SIGQUIT,CtrlSlashHandler);
}

void CtrlCHandler(int s)
{

if(CtrlC_Count<2) /*we only want to capture the first two times that Ctrl+C is pressed*/
{
CtrlC_Count++; //increment the CTRL+C counter
lives--; //decrement the lives counter
}
if(lives==0) //if out of lives, return for exiting the program
{
return;
}
signal(SIGINT,CtrlCHandler);

}
int main()
{
signal(SIGINT,CtrlCHandler); /*handle Ctrl+C, signal code is SIGINT*/
// signal(SIGQUIT,CtrlSlashHandler); /*handle Ctrl+, signal code is SIGQUIT*/
while(1)
{
Sleep(1000); /*you may need to change this to Sleep(1) on *nix as
Sleep() on windows takes the parameter in milliseconds instead of seconds*/
switch(lives)
{
case 4: printf("%d Lives: Still going strong! ",lives);
break;
case 3: printf("%d Lives: Hit, still going! ",lives);
break;
case 2: printf("%d Lives: Wounded, still going! ",lives);
break;
case 1: printf("%d Life: Dying, still going! ",lives);
break;
case 0: printf("Dead! ");
break;
}
if(!lives) break; //end program if out of lives
}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote