/* Experiment 05 — fd_set is a bitmap. See the bits, then watch select() rewrite them. * * Build: cc -Wall -Wextra -Werror 05_fdset.c -o 05_fdset * Run: ./05_fdset * * Part 1 (pure macros): the set is just bits. FD_ZERO/SET/CLR/ISSET only flip * and read bits — no fd is created, closed, or checked. * * Part 2 (real syscall): two pipes — one with a byte waiting (readable), one * empty (not readable). Both bits go into the set; select() returns with ONLY * the readable one still marked. That is the destructive rewrite that makes * "rebuild or copy the set every loop" mandatory in mini_serv. * * Note: FD_SET(5) in part 1 does not create fd 5. If you pass select() a bit * whose fd is not actually open, select fails with -1 / EBADF. Bits are not fds. */ #include #include #include #include static void print16(const char *label, const fd_set *set) { int i; printf("%s\n ", label); i = 15; while (i >= 0) { printf("%d", FD_ISSET(i, set) ? 1 : 0); if (i % 8 == 0) printf(" "); i--; } printf(" (bits 15..0)\n"); } static int max_of(int a, int b) { if (a > b) return (a); return (b); } int main(void) { fd_set set; struct timeval tv; int ready[2]; int empty[2]; int r; printf("FD_SETSIZE = %d | sizeof(fd_set) = %zu bytes (%zu bits)\n", FD_SETSIZE, sizeof(fd_set), sizeof(fd_set) * 8); /* ---- part 1: the macros are only bit operations ------------------- */ FD_ZERO(&set); print16("FD_ZERO(&set):", &set); FD_SET(3, &set); FD_SET(5, &set); print16("after FD_SET(3) + FD_SET(5):", &set); printf("FD_ISSET(3)=%d FD_ISSET(4)=%d FD_ISSET(5)=%d\n", FD_ISSET(3, &set) != 0, FD_ISSET(4, &set) != 0, FD_ISSET(5, &set) != 0); FD_CLR(3, &set); print16("after FD_CLR(3):", &set); /* ---- part 2: select() with real file descriptors ------------------ */ if (pipe(ready) < 0 || pipe(empty) < 0) { perror("pipe"); return (1); } if (write(ready[1], "x", 1) != 1) { perror("write"); return (1); } printf("\nreal fds: readable pipe fd=%d (1 byte waiting), silent pipe fd=%d (empty)\n", ready[0], empty[0]); FD_ZERO(&set); FD_SET(ready[0], &set); FD_SET(empty[0], &set); printf("before select: FD_ISSET(readable)=%d FD_ISSET(silent)=%d\n", FD_ISSET(ready[0], &set) != 0, FD_ISSET(empty[0], &set) != 0); tv.tv_sec = 0; tv.tv_usec = 0; r = select(max_of(ready[0], empty[0]) + 1, &set, NULL, NULL, &tv); printf("select returned %d (number of ready fds)\n", r); printf("after select: FD_ISSET(readable)=%d FD_ISSET(silent)=%d <- non-ready bit GONE\n", FD_ISSET(ready[0], &set) != 0, FD_ISSET(empty[0], &set) != 0); printf("\nConclusion: select() is an in/out parameter that keeps only ready bits.\n" "mini_serv therefore rebuilds or copies its set before every call.\n"); close(ready[0]); close(ready[1]); close(empty[0]); close(empty[1]); return (0); }