po> 2&1对popen做了什么?

Aqu*_*irl 4 c popen

2>&1导致popen陷阱stderr.

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

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

P.P*_*.P. 6

它是一个shell构造.这意味着将stirect(>)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"
Run Code Online (Sandbox Code Playgroud)

popen()仅捕获stdout.因此,使用命令运行无法捕获来自其的消息stderr.

例如,用

  FILE *fp = popen("command", "r");
Run Code Online (Sandbox Code Playgroud)

stdoutcommand可以被捕获(读取使用fp).但有了这个

  FILE *fp = popen("command 2>&1", "r");
Run Code Online (Sandbox Code Playgroud)

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


效果与dup2(1,2);C 相同.

考虑

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

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

如果这是编译并运行如下:

# ./a.out >output
Run Code Online (Sandbox Code Playgroud)

这两行都将打印到一个名为的文件中output.

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

其他来源: