π»Console Application 2
Now we shall make a program which gives the user a hint every 5 secs until the user inputs something or terminates the program (whichever comes first)
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
//#define _XOPEN_SOURCE 700
int ANS = 0, SANS = 0;
// random shit no jutsu
int getRandom(int lower,int upper){
srand(time(NULL));
return (rand() % (upper - lower + 1)) + lower;
}
void showAnswer();
int generateQuestion();
void signal_handler(int signo){
if (signo == SIGUSR1)
printf("\nThis is very easy");
}
int main(int argc, char *argv[]){
pid_t id = fork();
if (id != 0){
while(1){
sleep(5);
kill(id, SIGUSR1);
}
}else{
struct sigaction sa = {0};
sa.sa_flags = SA_RESTART;
sa.sa_handler = &signal_handler;
sigaction(SIGUSR1, &sa, NULL);
ANS = generateQuestion();
scanf("%d", &SANS);
showAnswer();
kill(getppid(), SIGINT);
}
return 0;
}
int generateQuestion(){
int x = getRandom(15,20);
int y = getRandom(5,10);
int c = getRandom(0,2);
char op[3] = {'+','-','*'};
printf("Enter the answer of the following problem\n%d %c %d = ",x,op[c],y);
switch (c){
case 0: return x+y;
case 1: return x-y;
case 2: return x*y;
}
}
void showAnswer(){
printf("\nAnswer submitted = %d\n", SANS);
printf("Correct answer = %d", ANS);
printf("\n%s answer submitted within time !!!",(SANS == ANS)?"Correct":"Wrong");
}Outputs
Last updated