如果stdout是文件,则stdout重定向不起作用 [英] stdout redirection does not work if stdout is a file

查看:234
本文介绍了如果stdout是文件,则stdout重定向不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在从用Fortran编写的外部库中调用嘈杂的函数之前,我正在使用以下代码来重定向stdout:

I am using code like the following to redirect stdout before calling a noisy function from an external library written in Fortran:

// copy standard output
out = dup(STDOUT_FILENO);

// close standard output
close(STDOUT_FILENO);

// use log file as standard output
log = open(log_file, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
if(log != STDOUT_FILENO)
    fprintf(stderr, "could not create log file %s", log_file);

// call the library function that uses a lot of printf
func();

// restore original standard output
dup2(out, STDOUT_FILENO);

// close copy of standard output
close(out);

总结一下我对上述代码段的意图:复制标准输出,关闭标准输出(释放文件描述符0),打开文件(使用最低文件描述符= 0 =标准输出),运行带有重定向标准输出的代码,并重置标准输出.

To summarise my intention of the above code snippet: copy stdout, close stdout (frees file descriptor 0), open file (uses lowest file descriptor = 0 = stdout), run code with redirected stdout, and reset stdout.

当我使用终端作为标准输出运行代码时,这非常好用.但是,当我将stdout设置为文件(使用$ mycode > myfile.txt)时,重定向失败,并且最终在myfile.txt中而不是日志文件中显示了func()的输出.这怎么可能?

This works perfectly well when I run my code using the terminal as stdout. However, when I set stdout to a file (using $ mycode > myfile.txt) the redirection fails, and I end up with the output of func() in myfile.txt instead of the log file. How is this possible?

推荐答案

在使用dup2恢复原始标准输出之前,需要执行fflush(stdout).

You need to do fflush(stdout) before you restore the original stdout with dup2.

它与终端一起使用的原因是因为stdout是为终端进行行缓冲的.因此,您的输出将立即刷新到重定向的文件.但是,当您使用stdout将程序启动到文件时,stdout会被完全缓冲,因此您的func输出将在缓冲区中等待刷新.当您不刷新而恢复原始标准输出时,程序退出时,输出将被写入原始标准输出.

The reason it works with a terminal is because stdout is line buffered for a terminal. So your output gets flushed immediately to the redirected file. But when you start your program with stdout to a file, stdout becomes fully buffered, so your func output will be in a buffer waiting to be flushed. When you restore the original stdout without flushing, the output gets written to the original stdout when the program exits.

这篇关于如果stdout是文件,则stdout重定向不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆