/*
 * 03_timer_loop.c —— 用 select 的 timeout 当定时器
 *
 * 编译: gcc 03_timer_loop.c -o timer_loop
 * 运行: ./timer_loop
 *
 * 思路: 把 timeout 设成 1 秒，每次返回都打印一次 tick；
 *       同时还能监听 stdin，输入 'q' 退出。
 *       这是没有专用 timerfd 的年代，select 兼任定时器的常用技巧。
 */

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

int main(void) {
    fd_set rfds;
    struct timeval tv;
    int ticks = 0;

    printf("⏱  每秒打印一次 tick；输入 q + 回车退出\n");
    fflush(stdout);

    while (1) {
        FD_ZERO(&rfds);
        FD_SET(STDIN_FILENO, &rfds);
        tv.tv_sec  = 1;
        tv.tv_usec = 0;

        int n = select(STDIN_FILENO + 1, &rfds, NULL, NULL, &tv);
        if (n < 0) { perror("select"); break; }

        if (n == 0) {
            /* 超时 = 一个 tick */
            printf("🔔 tick #%d\n", ++ticks);
            fflush(stdout);
        } else {
            /* stdin 有数据 */
            char buf[64];
            ssize_t r = read(STDIN_FILENO, buf, sizeof(buf));
            if (r > 0 && buf[0] == 'q') {
                printf("👋 收到 q，退出\n");
                break;
            }
            printf("📨 你输入了: %.*s", (int)r, buf);
        }
    }
    return 0;
}
