使用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/