> For the complete documentation index, see [llms.txt](https://octave-1.gitbook.io/c-unix/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://octave-1.gitbook.io/c-unix/applications/console-application-1.md).

# Console Application 1

Make a console application that takes an input only if it within a given time-span (5s in our case) and terminates after that

The following code generates a random question and stops taking input after 5s

```c
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>

int isChanged = 0, 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();

int main(int argc, char *argv[]){
    pid_t id = fork();
    if (id != 0){
        sleep(5);
        
        showAnswer();
        kill(id, SIGINT);
    }else{
        ANS = generateQuestion();
        scanf("%d", &SANS);
        isChanged = 1;

        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(){
    if(isChanged == 1){
        printf("\nAnswer submitted = %d\n", SANS);
        printf("Correct answer = %d", ANS);
        printf("\n%s answer submitted within time !!!",(SANS == ANS)?"Correct":"Wrong");
    }else printf("\n\nTimes up !!!\n");
}
```

## Outputs

```
Enter the answer of the following problem
16 - 6 = 15

Answer submitted = 15
Correct answer = 10
Wrong answer submitted within time !!!
```

```
Enter the answer of the following problem
20 * 10 = 200

Answer submitted = 200
Correct answer = 200
Correct nswer submitted within time !!!
```

```
Enter the answer of the following problem
17 * 7 = 

Times up !!!
```

```
Enter the answer of the following problem
15 + 5 = 

Times up !!!
```

Compile and run

```
gcc question.c -o qs && ./qs
```

Memory leak check with **valgrind**

```
valgrind ./qs --leak-check=full
```

{% file src="/files/zDVucXQ1nvVZhpibcd7b" %}
**Check logs for debug info**
{% endfile %}
