【问题标题】:How to tell if stderr has been redirected in Windows?如何判断 stderr 是否已在 Windows 中重定向?
【发布时间】:2017-06-27 15:21:13
【问题描述】:

我希望我的程序在 stderr 连接到控制台和重定向到文件/管道时具有不同的行为。在 Unix 系统中,我可以只测试 isatty(STDERR_FILENO),但是在 Windows 中我该怎么做呢? MSVCRT 还有一个名为_isatty 的函数,它不能正常工作(例如,Detect NUL file descriptor (isatty is bogus))。我可以调用任何 Windows 或 NT API 来测试它吗?

【问题讨论】:

  • C 和 C++ 是不同的语言。你用哪个?
  • @Olaf:没关系。 Windows API 可以从 C 和 C++ 中使用。在 C 或 C++ 中寻求解决方案是标准做法(没有区别)。
  • @IInspectable:如果这是 WinAPI 的问题,它使用 C 绑定,因此这是一个 C 问题。
  • accepted answer from the question you linked to 有解决方案,只是你需要使用STD_ERROR_HANDLE 而不是STD_OUTPUT_HANDLE)。

标签: c++ c windows winapi console


【解决方案1】:
  1. 调用GetStdHandle 获取stderr 句柄。
  2. 将该句柄传递给GetFileType 以找出它是什么类型的文件。
  3. 如果返回FILE_TYPE_CHAR,则stderr 可能是一个控制台,但调用GetConsoleMode 进行检查。
  4. 如果GetConsoleMode 失败,则标准错误已被重定向到另一个字符设备,例如打印机。

【讨论】:

  • 这还不够,如proposed duplicate中所述。
  • 如果句柄不是字符设备,GetConsoleMode 会成功吗?如果不是,那么GetFileType 是多余的。
【解决方案2】:

对我来说,最简单的方法是使用fseek(stderr, 0, SEEK_CUR),如果stderr 被重定向到文件,则返回0,如果stderr 未被重定向,则返回<>0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-27
    • 1970-01-01
    • 1970-01-01
    • 2010-09-10
    • 1970-01-01
    • 2014-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多