1 /*	$NetBSD: fifo_rdwr_bug.c,v 1.1.1.1 2009/06/23 10:08:59 tron Exp $	*/
2 
3 /*++
4 /* NAME
5 /*	fifo_rdwr_bug 1
6 /* SUMMARY
7 /*	fifo server test program
8 /* SYNOPSIS
9 /*	fifo_rdwr_bug
10 /* DESCRIPTION
11 /*	fifo_rdwr_bug creates a FIFO and opens it read-write mode.
12 /*	On BSD/OS 3.1 select() will report that the FIFO is readable
13 /*	even before any data is written to it. Doing an actual read
14 /*	causes the read to block; a non-blocking read fails.
15 /* DIAGNOSTICS
16 /*	Problems are reported to the standard error stream.
17 /* LICENSE
18 /* .ad
19 /* .fi
20 /*	The Secure Mailer license must be distributed with this software.
21 /* AUTHOR(S)
22 /*	Wietse Venema
23 /*	IBM T.J. Watson Research
24 /*	P.O. Box 704
25 /*	Yorktown Heights, NY 10598, USA
26 /*--*/
27 
28 #include <sys_defs.h>
29 #include <sys/time.h>
30 #include <sys/param.h>
31 #include <sys/stat.h>
32 #include <stdio.h>
33 #include <fcntl.h>
34 #include <signal.h>
35 #include <unistd.h>
36 #include <stdlib.h>
37 #include <string.h>
38 
39 #define FIFO_PATH       "test-fifo"
40 #define perrorexit(s)   { perror(s); exit(1); }
41 
42 static void cleanup(void)
43 {
44     printf("Removing fifo %s...\n", FIFO_PATH);
45     if (unlink(FIFO_PATH))
46 	perrorexit("unlink");
47     printf("Done.\n");
48 }
49 
50 int     main(int unused_argc, char **unused_argv)
51 {
52     struct timeval tv;
53     fd_set  read_fds;
54     fd_set  except_fds;
55     int     fd;
56 
57     (void) unlink(FIFO_PATH);
58 
59     printf("Creating fifo %s...\n", FIFO_PATH);
60     if (mkfifo(FIFO_PATH, 0600) < 0)
61 	perrorexit("mkfifo");
62 
63     printf("Opening fifo %s, read-write mode...\n", FIFO_PATH);
64     if ((fd = open(FIFO_PATH, O_RDWR, 0)) < 0) {
65 	perror("open");
66 	cleanup();
67 	exit(1);
68     }
69     printf("Selecting the fifo for readability...\n");
70     FD_ZERO(&read_fds);
71     FD_SET(fd, &read_fds);
72     FD_ZERO(&except_fds);
73     FD_SET(fd, &except_fds);
74     tv.tv_sec = 1;
75     tv.tv_usec = 0;
76 
77     switch (select(fd + 1, &read_fds, (fd_set *) 0, &except_fds, &tv)) {
78     case -1:
79 	perrorexit("select");
80     default:
81 	if (FD_ISSET(fd, &read_fds)) {
82 	    printf("Opening a fifo read-write makes it readable!!\n");
83 	    break;
84 	}
85     case 0:
86 	printf("The fifo is not readable, as it should be.\n");
87 	break;
88     }
89     cleanup();
90     exit(0);
91 }
92