C使用dup2管道子级和父级

C使用dup2管道子级和父级,c,process,pipe,fork,dup2,C,Process,Pipe,Fork,Dup2,我正在练习将两个过程连接在一起。我想让两个进程使用两个管道相互通信。以下是我目前掌握的情况: #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <stdlib.h> int main(){ //setting up two pipes int pipe1[2]; int pipe2[2]

我正在练习将两个过程连接在一起。我想让两个进程使用两个管道相互通信。以下是我目前掌握的情况:

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

int main(){

  //setting up two pipes
  int pipe1[2];
  int pipe2[2];
  pipe(pipe1);
  pipe(pipe2);

  //setting up child and parent
  pid_t pid = fork();
  if(pid < 0){
    perror("fork failed\n");
    exit(-1);
  }
  if(pid == 0){
    printf("child\n");
    dup2(pipe1[1], STDOUT_FILENO);
    close(pipe1[1]);
    close(pipe1[0]);
    dup2(pipe2[0], STDIN_FILENO);
    close(pipe2[0]);
    close(pipe2[1]);
  }
  if(pid > 0){
    wait(NULL);
    printf("parent\n");
    dup2(pipe1[0], STDIN_FILENO);
    close(pipe1[0]);
    close(pipe2[1]);
    dup2(pipe2[1], STDOUT_FILENO);
    close(pipe2[0]);
    close(pipe2[1]);
  }

  return 0;
}
#包括
#包括
#包括
#包括
#包括
int main(){
//架设两条管道
int-pipe1[2];
int-pipe2[2];
管道(管道1);
管道(管道2);
//设置孩子和家长
pid_t pid=fork();
if(pid<0){
perror(“fork失败\n”);
出口(-1);
}
如果(pid==0){
printf(“child\n”);
dup2(管道1[1],标准文件号);
关闭(管道1[1]);
关闭(管道1[0]);
dup2(管道2[0],标准文件号);
关闭(管道2[0]);
关闭(管道2[1]);
}
如果(pid>0){
等待(空);
printf(“父项”);
dup2(管道1[0],标准文件号);
关闭(管道1[0]);
关闭(管道2[1]);
dup2(pipe2[1],标准文件号);
关闭(管道2[0]);
关闭(管道2[1]);
}
返回0;
}
我希望两个进程通过将一个进程的输入作为另一个进程的输出来相互通信。我的设置正确吗?如果是这样的话,如果我希望父级将整数发送给子级,子级对其执行操作,然后将它们发送回父级进行打印,那么我可以从这里转到哪里


谢谢。

如果您希望家长和孩子能够通过管道进行通信,则无需使用
dup2()
。在父级中打开的文件描述符在
fork()子级中也可用,因此在这样一个简单的场景中,您可以安全地直接引用管道的“端点”,而无需设置任何形式的I/O重定向…当然,如果您计划
exec(),情况会有所变化“正在调用子进程中的任何内容,您希望从
exec()”ed
二进制文件的输出最终进入管道。在这种情况下,使用
dup2()
(与您的代码类似,但更简单)进行I/O重定向可能是最简单的方法。另请参见:或其他教程。不过,一定要添加正确的错误检查!我只是仔细看了看,没有什么事情看起来太糟糕了。免责声明(“这只是一个视觉检查,我还没有真正尝试编译和运行它”)。也就是说,在苏的姐妹网站上询问这件事可能是值得的。祝你好运你能解释一下什么是
等待(空)
是用来做什么的?@user268396您能详细说明一下代码的用法吗?我不太明白你的意思。我还在学习C,但是你能解释一下为什么在重定向stdout并调用printf之后,任何字符串仍然会被打印到屏幕上吗?输出不应该重定向到管道中吗?还是我的理解不正确