summaryrefslogtreecommitdiff
path: root/reference/C/CONTRIB/OR_USING_C/05.3.c
diff options
context:
space:
mode:
Diffstat (limited to 'reference/C/CONTRIB/OR_USING_C/05.3.c')
-rw-r--r--reference/C/CONTRIB/OR_USING_C/05.3.c61
1 files changed, 61 insertions, 0 deletions
diff --git a/reference/C/CONTRIB/OR_USING_C/05.3.c b/reference/C/CONTRIB/OR_USING_C/05.3.c
new file mode 100644
index 0000000..9457d07
--- /dev/null
+++ b/reference/C/CONTRIB/OR_USING_C/05.3.c
@@ -0,0 +1,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);
+}
+