/*
 * 01_simple_poll.c —— 入门：poll 监听 stdin 5 秒
 *
 * 编译: gcc 01_simple_poll.c -o simple_poll
 * 运行: ./simple_poll
 *
 * 体会 events 和 revents 的"输入/输出"职责分离。
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <poll.h>

int main(void) {
    struct pollfd pfd;
    pfd.fd     = STDIN_FILENO;
    pfd.events = POLLIN;          /* 用户写: 我关心可读事件 */
    pfd.revents = 0;              /* 显式清零（实际不必，内核会覆盖） */

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

    int n = poll(&pfd, 1, 5000);  /* 第 3 个参数是 ms */

    if (n < 0) {
        perror("poll error");
        return 1;
    } else if (n == 0) {
        printf("😴 5 秒到了，啥也没等到\n");
    } else {
        /* 必须用按位与判断 —— revents 可能同时有多个事件 */
        if (pfd.revents & POLLIN) {
            char buf[256];
            ssize_t r = read(STDIN_FILENO, buf, sizeof(buf) - 1);
            if (r > 0) {
                buf[r] = '\0';
                printf("✅ 收到: %s", buf);
            }
        }
        if (pfd.revents & POLLERR) printf("⚠️ POLLERR\n");
        if (pfd.revents & POLLHUP) printf("⚠️ POLLHUP\n");
    }
    return 0;
}
