UNIX processes using C/C++
  • 🍴The fork system call
  • ⌚The wait system call
  • 🆔Process ID
  • 🔌Signals in UNIX
    • 🗄️Signal Handlers
  • 🥃Executing system commands
  • 📁Sharing information between processes
    • 🕚Bidirectional pipe
  • 🖥️Applications
    • 💻Console Application 1
    • 💻Console Application 2
  • ⚽Named pipe FIFO
Powered by GitBook
On this page
  1. Applications

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

#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
PreviousApplicationsNextConsole Application 2

Last updated 2 years ago

🖥️
💻
2KB
signals-log-1.txt
Check logs for debug info