summaryrefslogtreecommitdiff
path: root/reference/C/CONTRIB/OR_USING_C/05.3.c
blob: 9457d07e81a1b80111e47643442b09cf0214817e (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
56
57
58
59
60
61
#include <sys/types.h>
#include <sys/time.h>
#include <stdio.h>

main()
{
    int n, nfds;
    char buf[32];
    fd_set readfds;
    struct timeval tv;

    /*
     * We will be reading from standard input (file
     * descriptor 0), so we want to know when the
     * user has typed something.
     */
    FD_ZERO(&readfds);
    FD_SET(0, &readfds);

    /*
     * Set the timeout for 15 seconds.
     */
    tv.tv_sec = 15;
    tv.tv_usec = 0;

    /*
     * Prompt for input.
     */
    printf("Type a word; if you don't in 15 ");
    printf("seconds I'll use \"WORD\": ");
    fflush(stdout);

    /*
     * Now call select.  We pass NULL for
     * writefds and exceptfds, since we
     * aren't interested in them.
     */
    nfds = select(1, &readfds, NULL, NULL, &tv);

    /*
     * Now we check the results.  If nfds is zero,
     * then we timed out, and should assume the
     * default.  Otherwise, if file descriptor 0
     * is set in readfds, that means that it is
     * ready to be read, and we can read something
     * from it.
     */
    if (nfds == 0) {
        strcpy(buf, "WORD");
    }
    else {
        if (FD_ISSET(0, &readfds)) {
            n = read(0, buf, sizeof(buf));
            buf[n-1] = '\0';
        }
    }

    printf("\nThe word is: %s\n", buf);
    exit(0);
}