【问题标题】:What does 2>&1 do to popen?2>&1 对 popen 做了什么?
【发布时间】:2015-12-17 06:15:09
【问题描述】:

2>&1 导致popen 捕获stderr

我想了解它是如何工作的。

2、>、&、1在这里扮演什么角色?
我需要学习什么才能理解它们?

【问题讨论】:

标签: c popen


【解决方案1】:

这是一个外壳结构。这意味着将 (>) stderr(2) 重定向到 stdout(1) 所到之处。 1 是文件stdout 的文件描述符,2stderr 的文件描述符。

$ command 2>&1 #redirect stderr to stdout

$ command 1>&2 #redirect stdout to stderr

$ command 1>output 2>errors #redirect stdout to a file called "output"
                            #redirect stderr to a file called "errors"

popen() 仅捕获 stdout。因此运行命令 using 无法捕获来自其stderr 的消息。

例如,用

  FILE *fp = popen("command", "r");

只有stdout 中的command 可以被捕获(使用fp 读取)。但是有了这个

  FILE *fp = popen("command 2>&1", "r");

stdoutstderr 被捕获。但是通过这种重定向,stdoutstderr 无法区分,因为它们都是混合的。


效果与C语言中的dup2(1,2);相同。

考虑

#include <stdio.h>
#include <unistd.h>

int main(void)
{
   dup2(1,2);
   fprintf(stdout, "printed to stdout\n");
   fprintf(stderr, "printed to stderr\n");
}

如果编译并运行为:

# ./a.out >output

这两行都将打印到名为output 的文件中。

如果通过注释掉dup2() 行来运行代码。现在只有第一行将打印到文件中,第二行将打印在控制台上,即使它使用重定向仅捕获 stdout (&gt;)。

其他来源:

【讨论】:

    【解决方案2】:

    这是一个基本的文件描述符重定向。它将 stderr (2) 中的所有内容重定向到 (&gt;) stdout (&amp;1) 的文件描述符中。

    一件好事是您还可以同时将标准输出重定向到其他地方。
    例如:

    command >some-file 2>&1 
    

    有关文件描述符重定向的更多信息(在 unix/linux 中),我推荐https://www.gnu.org/software/bash/manual/html_node/Redirections.html

    【讨论】:

      【解决方案3】:

      MSDN 说:

      找到File.txt,然后重定向句柄1(即STDOUT)和 处理 2(即 STDERR)到 Search.txt,输入:findfile 文件.txt>search.txt 2

      还有

      /* Standard file descriptors.  */
      #define STDIN_FILENO    0   /* Standard input.  */
      #define STDOUT_FILENO   1   /* Standard output.  */
      #define STDERR_FILENO   2   /* Standard error output.  */
      

      您也可以参考2.7 Redirection 获取详细信息。

      进一步研究的链接:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-03-10
        • 1970-01-01
        • 2011-10-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-16
        相关资源
        最近更新 更多