summaryrefslogtreecommitdiff
path: root/entropy-watcher.c
blob: 2d6fe86463e6e6d6c1ff8f89dca2c37c869c4d33 (plain)
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
/**
 * Watch available kernel entropy. By default, it prints the available entrophy
 * every second, but this can be changed with arg1 (in milliseconds). You can
 * also press Enter to immediately print the current entrophy.
 *
 * Author: Peter Wu <lekensteyn@gmail.com>
 * Date: 2013-01-28
 */
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <poll.h>
#include <stdlib.h>
#include <stdbool.h>

#define FILENAME "/proc/sys/kernel/random/entropy_avail"

int main(int argc, char **argv) {
	char buff[32];
	ssize_t r;
	struct pollfd pfd;
	int fd;
	int print_interval_ms;

	print_interval_ms = 1000;
	if (argc > 1) {
		print_interval_ms = atoi(argv[1]);
	}

	fd = open(FILENAME, O_RDONLY);
	if (fd < 0) {
		perror(FILENAME);
		return 1;
	}

	pfd.fd = STDIN_FILENO;
	pfd.events = POLLIN;

	while ((r = read(fd, buff, sizeof(buff))) > 0) {
		write(STDOUT_FILENO, buff, r - 1);
		poll(&pfd, 1, print_interval_ms);
		lseek(fd, 0, SEEK_SET);
		if (pfd.revents == POLLIN) { /* pressed enter? */
			r = read(STDIN_FILENO, buff, sizeof(buff));
			if (r > 0 && buff[r - 1] == '\n')
				continue;
		}
		buff[0] = '\n';
		write(STDOUT_FILENO, buff, 1);
	}

	close(fd);

	return 0;
}