KDE
KDE

Reputation: 11

C program to print every 5 seconds and show total time when we exit

The program should print to the screen every 5 seconds and state "alive at %d milliseconds\n". When the user types in <Control><A> for the polling program or <Control><C> for the interrupt version, the program should stop and output:

program terminated by user. Total time is %d milliseconds %d seconds\n.

My Program:

#include <signal.h>
#include <stdio.h>
#include <stdbool.h>
#include <unistd.h>
#include <sys/time.h>
#include <time.h>

volatile sig_atomic_t print_flag = false;

void handle_alarm( int sig ) {
  print_flag = true;
}


int main() {
    struct timeval start, stop;
    double secs = 0;
    char key_press;
    char input_key;
    int ascii_value;
    float time_taken;
    clock_t t;
    t = clock();

    gettimeofday(&start, NULL);

    signal( SIGALRM, handle_alarm );
    alarm( 5 ); 

    for (;;) {


      if ( print_flag ) {
        print_flag = false;
        alarm( 5 );
        gettimeofday(&stop, NULL);
        secs = (double)(stop.tv_usec - start.tv_usec) / 1000000 + (double)(stop.tv_sec - start.tv_sec) * 1000;
        printf("Alive at %f ms \n",secs);
        input_key=getchar();
        ascii_value=input_key;
        if(ascii_value==1) {
          t = clock() - t;
          time_taken = ((float)t)/CLOCKS_PER_SEC; // in seconds
          printf("total time taken= %f sec", time_taken);
          break;
        }
      }
    }
}

I want the program to run continuously but when I press ctrl a it should terminate. The program prints "Alive at 5000.000 ms and stops printing. The program prints infinitely every 5 seconds if I don't add the code for terminating using ctrl A. How to make it work?

Upvotes: 0

Views: 1473

Answers (2)

metl wolf
metl wolf

Reputation: 91

When you ask for input in this way, you are using synchronous blocking I/O. The process hangs until input is given. If you wish for your program to continue functioning while waiting for input you need to delve into asynchronous non-blocking I/O. Look up the select() function

https://en.wikipedia.org/wiki/Asynchronous_I/O

https://www.gnu.org/software/libc/manual/html_node/Waiting-for-I_002fO.html

Upvotes: 1

babon
babon

Reputation: 3774

After you do print_flag = false; in the for loop, you never set print_flag back to true again. Hence, the code in the if ( print_flag ) block is executed only once.

How to make it work?

To make it work, you need to set print_flag to true before you check whether it is true.

Upvotes: 0

Related Questions