我希望能够判断我的程序的标准输出是否被重定向到文件/设备,或者是否仍然正常打印在屏幕上。如何在C语言中实现这一点?
更新1:从评论中得知,这似乎取决于系统。如果是这样,那么如何在符合posix标准的系统中实现这一点?
也许是 isatty(stdout)
?
编辑:正如Roland和tripleee所建议的那样,更好的答案是isatty(STDOUT_FILENO)
。
_isatty()
是 ISO C。 - Joseph Quinseyisatty(1)
可以很好地工作(STDOUT_FILENO
根据定义为1,所有shell程序员都非常清楚)。 - R.. GitHub STOP HELPING ICEisatty...
误导了。这个POSIX函数已经被弃用了。请使用符合ISO C++标准的_isatty
。 - Joseph Quinsey查找 isatty
函数,以及更一般的 fileno
函数。
如果可以使用Linux特定的解决方案,您可以检查进程下的符号链接,位于/proc
目录下。例如:
$ exec 3>/dev/null
$ ls -l /proc/$$/fd
total 0
lrwx------ 1 root root 64 Sep 12 03:28 0 -> /dev/pts/1
lrwx------ 1 root root 64 Sep 12 03:29 1 -> /dev/pts/1
lrwx------ 1 root root 64 Sep 12 03:29 2 -> /dev/pts/1
lrwx------ 1 root root 64 Sep 12 03:29 255 -> /dev/pts/1
l-wx------ 1 root root 64 Sep 12 03:29 3 -> /dev/null
你可能想要查看这个:
http://www.cplusplus.com/reference/clibrary/cstdio/freopen/
我在引用链接中的内容:freopen
Reopen stream with different file or mode
freopen first tries to close any file already associated with the stream given as third parameter and disassociates it.
Then, whether that stream was successfuly closed or not, freopen opens the file whose name is passed in the first parameter, filename, and associates it with the specified stream just as fopen would do using the mode value specified as the second parameter.
This function is specially useful for redirecting predefined streams like stdin, stdout and stderr to specific files.
虽然我不确定这是否会帮助您首先找出它指向的内容。
ls
那样基于这个条件进行任何魔法操作。请阅读Rob Pike的《Unix环境编程》获取详细信息。 - Roland Illig