/*
 * 01_epoll_basic.c —— epoll 三剑客最小演示
 *
 * 编译: gcc 01_epoll_basic.c -o epoll_basic
 * 运行: ./epoll_basic
 * 玩法: 5 秒内输入任意文字回车
 *
 * 仅监听 stdin，目的是看清 create/ctl/wait 的最小调用形态。
 */

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

int main(void) {
    /* 1) 创建 epoll 实例（这本身也是个 fd，会随进程退出关闭） */
    int epfd = epoll_create1(EPOLL_CLOEXEC);
    if (epfd < 0) { perror("epoll_create1"); return 1; }

    /* 2) 把 stdin 注册进去，关心 EPOLLIN 事件 */
    struct epoll_event ev;
    ev.events  = EPOLLIN;
    ev.data.fd = STDIN_FILENO;
    if (epoll_ctl(epfd, EPOLL_CTL_ADD, STDIN_FILENO, &ev) < 0) {
        perror("epoll_ctl"); return 1;
    }

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

    /* 3) 等事件 */
    struct epoll_event events[8];
    int n = epoll_wait(epfd, events, 8, 5000);   /* timeout = 5000 ms */

    if (n < 0)      perror("epoll_wait");
    else if (n == 0) printf("😴 5 秒到了，啥也没等到\n");
    else {
        for (int i = 0; i < n; i++) {
            if (events[i].data.fd == STDIN_FILENO) {
                char buf[256];
                ssize_t r = read(STDIN_FILENO, buf, sizeof(buf) - 1);
                if (r > 0) {
                    buf[r] = '\0';
                    printf("✅ epoll 通知 stdin 可读，读到: %s", buf);
                }
            }
        }
    }

    close(epfd);    /* 关闭 epoll 实例 */
    return 0;
}
