/*
 * 01_simple_select.c —— 入门：select 监听 stdin 5 秒超时
 *
 * 编译: gcc 01_simple_select.c -o simple_select
 * 运行: ./simple_select
 * 玩法: 5 秒内输入任意文字回车，或啥都不做等超时
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/select.h>
#include <errno.h>

int main(void) {
    fd_set rfds;
    struct timeval tv;
    int retval;

    FD_ZERO(&rfds);
    FD_SET(STDIN_FILENO, &rfds);

    tv.tv_sec  = 5;
    tv.tv_usec = 0;

    printf("⏰ 5 秒内输入任意文字...\n");
    fflush(stdout);

    /*
     * select 的第一个参数是「最大 fd + 1」
     * STDIN_FILENO == 0，所以这里是 1
     */
    retval = select(STDIN_FILENO + 1, &rfds, NULL, NULL, &tv);

    if (retval == -1) {
        perror("select error");
        return EXIT_FAILURE;
    } else if (retval == 0) {
        printf("😴 5 秒到了，啥也没等到\n");
    } else {
        if (FD_ISSET(STDIN_FILENO, &rfds)) {
            char buf[256];
            ssize_t n = read(STDIN_FILENO, buf, sizeof(buf) - 1);
            if (n > 0) {
                buf[n] = '\0';
                printf("✅ 收到 %ld 字节: %s", n, buf);
            }
        }
    }
    return EXIT_SUCCESS;
}
