/* Experiment 04 — select() with TWO sources: your keyboard (stdin) and a * listening socket. You are watching the waiting room in action. * * Build: cc -Wall -Wextra -Werror 04_select_two.c -o 04_select_two * Run: ./04_select_two 8081 * * Then, in order: * - type something + Enter here -> "stdin ready" * - nc 127.0.0.1 8081 -> "listener ready", it accepts, * reads one line, closes that client * - Ctrl-D in this terminal -> stdin EOF, program exits * * Lesson: select() blocks until ANY watched fd is ready, then tells you which * one(s) via FD_ISSET. This is the exact heartbeat of mini_serv. */ #include #include #include #include #include #include #include int main(int argc, char **argv) { struct sockaddr_in addr; // socket fd_set rfds; // a set of fds to read char buf[128]; // the buffer ssize_t n; int sfd; // socket fd int cfd; // connection fd int maxfd; // max number of fds if (argc != 2) { fprintf(stderr, "usage: %s PORT\n", argv[0]); return (1); } setvbuf(stdout, NULL, _IOLBF, 0); sfd = socket(AF_INET, SOCK_STREAM, 0); //create a stream socket if (sfd < 0) { perror("socket"); return (1); } memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; // add the configrations addr.sin_addr.s_addr = htonl(2130706433); addr.sin_port = htons(atoi(argv[1])); if (bind(sfd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { perror("bind"); return (1); } if (listen(sfd, 10) < 0) { perror("listen"); return (1); } maxfd = sfd; /* stdin is fd 0, so the highest is the socket */ printf("watching stdin(0) and the listener(fd %d). Type here, or nc 127.0.0.1 %s\n", sfd, argv[1]); while (1) { FD_ZERO(&rfds); /* select destroys the set: rebuild every loop */ FD_SET(0, &rfds); FD_SET(sfd, &rfds); if (select(maxfd + 1, &rfds, NULL, NULL, NULL) < 0) continue ; if (FD_ISSET(0, &rfds)) { n = read(0, buf, sizeof(buf) - 1); if (n <= 0) { printf("stdin EOF — bye.\n"); break ; } buf[n] = 0; printf("stdin ready: [%s]", buf); } if (FD_ISSET(sfd, &rfds)) { cfd = accept(sfd, NULL, NULL); if (cfd < 0) continue ; printf("listener ready: accepted fd %d — reading one line...\n", cfd); n = recv(cfd, buf, sizeof(buf) - 1, 0); if (n > 0) { buf[n] = 0; printf(" got: [%s]", buf); } else printf(" recv returned %zd (EOF/error)\n", n); close(cfd); } } close(sfd); return (0); }