epoll_wait()阻止打印到stdout

时间:2015-11-21 19:22:08

标签: c sockets stdout epoll

当使用epoll_wait时,似乎“吃掉”写入stdout的所有内容并延迟打印直到epoll_wait收到事件后,即使我在调用之前尝试打印关于与epoll相关的任何事情(它甚至可能在我的主要方法的开头,它仍然不会被打印)。

直到epoll_wait收到事件后才会显示的打印件示例:

printf("This doesn't get printed. ");
fprintf(stdout, "This doesn't get printed either.");
ev.events = EPOLLIN;
ev.data.fd = some_sock_fd; // Same with STDIN_FILENO
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, some_sock_fd, &ev) == -1) {
    perror("epoll_ctl");
    exit(EXIT_FAILURE);
}

for (;;) {
    rc = epoll_wait(epoll_fd, &ev, 1, -1);
    // This is where it gets printed

写入stderr正常工作,但如何写入stdout?如何阻止epoll_wait阻止打印到stdout

1 个答案:

答案 0 :(得分:0)

这个问题似乎与epoll_wait无关。以下是违规代码的摘要:

// Since there's no newline, the following stays in the buffer
printf("Some print without newline.");

for (;;) {
    // At this point, the buffer has not been flushed,
    // and epoll_wait blocks the output
    rc = epoll_wait(epoll_fd, &ev, 1, -1);

使用fflush(stdout) 此代码的解决方案,因为缓冲与epoll_wait无关,但与用户空间如何缓冲stdout:

// Since there's no newline, the following stays in the buffer
printf("Some print without newline.");

// Forces a write of user-space buffered data for stdout
fflush(stdout);

for (;;) {
    // At this point, the buffer has not been flushed,
    // and epoll_wait blocks the output
    rc = epoll_wait(epoll_fd, &ev, 1, -1);

总而言之,这似乎是在一个本来应该是显而易见的问题的错误位置。