c - epoll_wait() 阻止打印到标准输出

标签 c sockets stdout epoll

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

直到 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

最佳答案

该问题似乎与 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);

总而言之,这似乎是一个在错误的地方寻找本应显而易见的问题的情况。

关于c - epoll_wait() 阻止打印到标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33847562/

相关文章:

c - 合并排序未显示正确的输出

c - 将代码加载到 GPU(Intel Sandy Bridge)

java - Android - 关闭特定的蓝牙套接字

python - 如何在 pyzmq 中使用 inproc 传输?

file - ffmpeg:哪些文件格式支持标准输入使用?

Python:在个人标准输出上编辑文本 - 双倍文本

c - 通过有效负载以外的方法在 Linux UDP 套接字之间交换任意数据

c - 在c linux中重启父进程

c - c中使用fork()处理socket中多个客户端的逻辑问题

bash - 缩进长行标准输出