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



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

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
int main(){
printf("Starting Testn");
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 pipen");    //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没有被正确复制,因为我得到了";管内";在";收到:"但是dup2((调用没有抛出任何错误。

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

代码有几个问题:

  1. dup2(1,myPipe[1])中,参数是前后排列的。这使得CCD_ 2与CCD_ 3相同。但相反,你需要它反过来:dup2(myPipe[1],1)

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

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

最新更新