// 演示非阻塞 read：没数据时立刻返回 -1，errno 是 EAGAIN；有数据时正常读到。
#include <fcntl.h>
#include <sys/socket.h>
#include <unistd.h>

#include <cerrno>
#include <cstdio>
#include <cstring>

int main() {
    // socketpair 创建一对互相连通的 socket：往 sv[0] 写的，能从 sv[1] 读到
    int sv[2];
    socketpair(AF_UNIX, SOCK_STREAM, 0, sv);

    // 把 sv[1] 设成非阻塞
    int flags = fcntl(sv[1], F_GETFL);
    fcntl(sv[1], F_SETFL, flags | O_NONBLOCK);

    char buf[100];
    ssize_t n = read(sv[1], buf, sizeof(buf));  // 还没人写，阻塞的话会永远卡在这里
    printf("1st read returned %zd, errno = %d (%s)\n", n, errno, strerror(errno));
    printf("EAGAIN = %d, so this means: no data right now, try again later\n", EAGAIN);

    write(sv[0], "hello", 5);
    n = read(sv[1], buf, sizeof(buf));
    printf("2nd read returned %zd: %.*s\n", n, static_cast<int>(n), buf);

    close(sv[0]);  // 关闭另一端
    n = read(sv[1], buf, sizeof(buf));
    printf("3rd read returned %zd (peer closed)\n", n);
    close(sv[1]);
    return 0;
}
