aboutsummaryrefslogtreecommitdiffstats
path: root/src/io_helper.c
blob: f4fa088a70f261b487b32ad5a1eaec1e5af5d766 (plain) (blame)
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
#include <stdlib.h>
#include <sys/select.h>

int timed_read(int timeout)
{
    char byte;

    if (timeout >= 0) {
        fd_set readfds;
        struct timeval t;

        FD_ZERO(&readfds);
        FD_SET(0, &readfds);

        t.tv_sec  = timeout / 1000000;
        t.tv_usec = timeout % 1000000;

        if (select(1, &readfds, NULL, NULL, &t) == 1) {
            if (read(0, &byte, 1) == 1) {
                return byte;
            }
            else {
                return -1;
            }
        }
        else {
            return -1;
        }
    }
    else {
        if (read(0, &byte, 1) == 1) {
            return byte;
        }
        else {
            return -1;
        }
    }
}