Ticket #3148: select-stdin.c

File select-stdin.c, 2.0 KB (added by bhaible, 15 years ago)

test program, to be run in a terminal

Line 
1/* Test of select() substitute, reading from stdin.
2 Copyright (C) 2008 Free Software Foundation, Inc.
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 3 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
16
17/* Written by Bruno Haible <bruno@clisp.org>, 2008. */
18
19#include <stdio.h>
20#include <stdlib.h>
21#include <sys/select.h>
22#include <sys/time.h>
23#include <unistd.h>
24
25int
26main ()
27{
28 printf ("Applying select() from standard input. Press Ctrl-C to abort.\n");
29 for (;;)
30 {
31 struct timeval before;
32 struct timeval after;
33 unsigned long spent_usec;
34 fd_set readfds;
35 struct timeval timeout;
36 int ret;
37
38 gettimeofday (&before, NULL);
39
40 FD_ZERO (&readfds);
41 FD_SET (0, &readfds);
42 timeout.tv_sec = 0;
43 timeout.tv_usec = 500000;
44 ret = select (1, &readfds, NULL, NULL, &timeout);
45
46 gettimeofday (&after, NULL);
47 spent_usec = (after.tv_sec - before.tv_sec) * 1000000
48 + after.tv_usec - before.tv_usec;
49
50 if (ret < 0)
51 {
52 perror ("select failed");
53 exit (1);
54 }
55 if ((ret == 0) != ! FD_ISSET (0, &readfds))
56 {
57 fprintf (stderr, "incorrect return value\n");
58 exit (1);
59 }
60 if (ret == 0)
61 {
62 if (spent_usec < 250000)
63 {
64 fprintf (stderr, "returned too early\n");
65 exit (1);
66 }
67 /* Timeout */
68 printf ("."); fflush (stdout);
69 }
70 else
71 {
72 char c;
73
74 printf ("Input available! Trying to read 1 byte...\n");
75 read (0, &c, 1);
76 }
77 }
78}