1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
#define _POSIX_C_SOURCE 199309L
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <termios.h>
#include <sys/ioctl.h>
struct termios termios_saved;
void restore_termios()
{
tcsetattr(0, TCSAFLUSH, &termios_saved);
}
void set_termios()
{
struct termios my_termios_settings;
if (tcgetattr(0, &termios_saved) == 0)
atexit(restore_termios);
else
exit(EXIT_FAILURE);
my_termios_settings = termios_saved;
my_termios_settings.c_lflag &= ~(ICANON|ECHO);
tcsetattr(0, TCSAFLUSH, &my_termios_settings);
}
int kbhit()
{
struct termios term;
tcgetattr(0, &term);
struct termios term2 = term;
term2.c_lflag &= ~ICANON;
tcsetattr(0, TCSANOW, &term2);
int byteswaiting;
ioctl(0, FIONREAD, &byteswaiting);
tcsetattr(0, TCSANOW, &term);
return byteswaiting > 0;
}
int main()
{
set_termios();
srand(time(0));
struct timespec ts = {0, 100000000}; // 1/10 second
int c = 0;
while (c != '1' && c != '2')
{
puts("Press (1) for a stream of random numbers. Press (2) to quit.");
c = getchar();
}
while (c == '1')
{
float r = rand() / (float)RAND_MAX;
printf("%f\n", r);
nanosleep(&ts, NULL);
if (kbhit() && getchar() == '2')
c = '2';
}
return 0;
}
| |