使用 dup2 复制标准输出后无法读取管道

can't read pipe after using dup2 to copy stdout

我正在尝试使用管道将 stdout 重定向到管道中并稍后读取。稍后我会将其与 fork() 一起使用,其中子进程启动我需要与之通信的不同程序。这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>

int main(){
printf("Starting Test\n");

int myPipe[2], nbytes;
char readbuffer[80];

pipe(myPipe);

int backup = dup(1);    //store stdout
if (dup2(1,myPipe[1])< 1){printf("error");}     //copy stdout in the input end of my pipe
printf("in pipe\n");    //print something in stdout -> in my pipe
nbytes = read(myPipe[0],readbuffer,sizeof(readbuffer)); //read output of my pipe

dup2(myPipe[1],backup); // restore stdout
printf("recived: %s",readbuffer);   //prit out what I recived

return 0;
}

我希望它打印出来:

Starting Test
recived: in pipe

但我得到的输出是:

Starting Test
in pipe
recived: @����U

所以我认为 stdout 没有被正确复制,因为我在“收到:...”之前得到了“in pipe”但是 dup2() 调用没有抛出任何错误。

我读了一些教程,主要是这一篇https://tldp.org/LDP/lpg/node11.html但是我找不到我的错误...谢谢你的帮助!

代码有几个问题:

  1. dup2(1,myPipe[1])中参数从后到前。这使得 mypipe[1]1 相同。但相反,你需要它是相反的:dup2(myPipe[1],1)

  2. dup2(myPipe[1],backup)也是错误的。这使得 backupmypipe[1] 相同。您想要的是使 1 与备份相同:dup2(backup, 1).

  3. 问题较小,但 printf 不输出 NUL 字符。所以 read 不会产生有效的 NUL 终止字符串。通过初始化解决:char readbuffer[80] = "";