cmkl_assignments/fall-2024/sys-arch/sys-102/00040/source/polling.c

57 lines
1.1 KiB
C
Raw Permalink Normal View History

#include <stdio.h>
#include <termios.h>
#include <unistd.h>
2024-11-18 23:37:15 +07:00
#include <time.h>
int main()
{
2024-11-18 23:37:15 +07:00
clock_t start, end;
double cpu_time_used;
// Set start to current CPU time
start = clock();
int c;
int flag = 0;
2024-11-18 23:37:15 +07:00
int laps = 0;
/*
THIS IS A REPLACEMENT FOR THE _KBHIT FUNCTION
2024-11-18 23:37:15 +07:00
*/
// These structs are for saving tty parameters
static struct termios old_term, new_term;
// Get parameters associated with the tty
// Set the new tty parameters to the old one
tcgetattr(STDIN_FILENO, &old_term);
new_term = old_term;
// Set the new tty parameters to canonical mode
new_term.c_lflag &= ~(ICANON);
// Set tty attributes
tcsetattr(STDIN_FILENO, TCSANOW, &new_term);
// Get character input by user
2024-11-18 23:37:15 +07:00
while ((c = getchar()) != EOF && laps < 10)
{
2024-11-18 23:37:15 +07:00
// Flip the flag
flag = !flag;
2024-11-18 23:37:15 +07:00
laps++;
printf("\n");
printf("Flag: %d\n", flag);
}
// Done retriving input
// Set tty parameters back to old tty parameters
tcsetattr(STDIN_FILENO, TCSANOW, &old_term);
2024-11-18 23:37:15 +07:00
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("CPU Time: %f\n", cpu_time_used);
return 0;
}