8322 nl: misleading-indentation
[unleashed/tickless.git] / usr / src / test / libc-tests / tests / select / select_test.c
blobf6af3718cbe87e28f8b62511337da3ad1c549bc1
1 /*
2 * This file and its contents are supplied under the terms of the
3 * Common Development and Distribution License ("CDDL"), version 1.0.
4 * You may only use this file in accordance with the terms of version
5 * 1.0 of the CDDL.
7 * A full copy of the text of the CDDL should have accompanied this
8 * source. A copy of the CDDL is also available via the Internet at
9 * http://www.illumos.org/license/CDDL.
12 /* Copyright 2016, Richard Lowe. */
14 #include <sys/select.h>
15 #include <sys/stat.h>
16 #include <sys/time.h>
17 #include <sys/types.h>
19 #include <err.h>
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
27 void
28 diff_sets(fd_set *a, fd_set *b, size_t size)
30 for (int i = 0; i < size; i++) {
31 if (FD_ISSET(i, a) != FD_ISSET(i, b))
32 printf("fd %d: %d should be %d\n", i, FD_ISSET(i, a),
33 FD_ISSET(i, b));
37 void
38 print_set(fd_set *a, size_t size)
40 for (int i = 0; i < size; i++) {
41 if (FD_ISSET(i, a))
42 putc('1', stdout);
43 else
44 putc('0', stdout);
47 putc('\n', stdout);
50 int
51 main(int argc, char **argv)
53 struct timeval tv = {0, 0};
54 fd_set check, proto;
55 fd_set *sread = NULL, *swrite = NULL, *serr = NULL;
56 int null, zero, maxfd = -1, nfds;
57 char buf[1];
59 if (argc != 2)
60 errx(1, "usage: select_test <number of fds>");
62 nfds = atoi(argv[1]);
63 if (errno != 0)
64 err(1, "couldn't convert %s to int", argv[1]);
66 if (nfds > FD_SETSIZE)
67 errx(1, "can't have more fds than FD_SETSIZE %d", FD_SETSIZE);
69 FD_ZERO(&proto);
70 FD_ZERO(&check);
72 switch (arc4random_uniform(3)) {
73 case 0:
74 sread = &check;
75 break;
76 case 1:
77 swrite = &check;
78 break;
79 case 2:
80 serr = &check;
81 break;
84 closefrom(3);
86 if ((null = open("/dev/null", O_RDONLY)) == -1)
87 err(1, "couldn't open /dev/null");
88 read(null, &buf, 1);
89 read(null, &buf, 1);
91 if ((zero = open("/dev/zero", O_RDWR)) == -1)
92 err(1, "couldn't open /dev/zero");
94 for (int i = zero; i < (zero + nfds); i++) {
95 int fd = (serr != NULL) ? null : zero;
96 if (arc4random_uniform(100) > 90) {
97 FD_SET(i, &proto);
100 if (dup2(fd, i) == -1)
101 err(1, "couldn't dup fd to fd %d", i);
102 maxfd = i;
105 if (swrite != NULL)
106 puts("write");
107 else if (sread != NULL)
108 puts("read");
109 else if (serr != NULL)
110 puts("err");
112 print_set(&proto, 80);
114 memcpy(&check, &proto, sizeof (check));
116 if (select(maxfd + 1, sread, swrite, serr, &tv) == -1)
117 err(1, "select failed");
119 if (memcmp(&check, &proto, sizeof (check)) != 0) {
120 diff_sets(&check, &proto, sizeof (check));
121 warnx("fd set mismatch: check: %p proto: %p", &check, &proto);
122 abort();
125 return (0);