【发布时间】:2018-09-23 06:30:56
【问题描述】:
我正在尝试编写一个程序,允许进程与其子进程进行双向通信,即它可以向子进程发送消息,也可以从子进程接收消息。我第一次尝试创建 2 个管道并将管道的每一端链接到父子标准输入和标准输出:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
int firstPipe[2];
int secondPipe[2];
if (pipe(firstPipe) < 0) {
perror("pipe");
exit(1);
}
if (pipe(secondPipe) < 0) {
perror("pipe");
exit(1);
}
if (fork() != 0) { // child
dup2(firstPipe[0], 0);
dup2(secondPipe[1], 1);
char input[70];
printf("Mr. Stark...");
fgets(input, 70, stdin);
fprintf(stderr, "%s I don't wanna go...\n", input);
} else { // parent
dup2(secondPipe[0], 0);
dup2(firstPipe[1], 1);
char message[70];
fgets(message, 70, stdin);
printf("%s I don't feel so good...", message);
}
return 0;
}
这个程序应该是从孩子发消息给家长,然后家长给孩子发回复,然后孩子打印最终结果(Stark先生...我感觉不太好...我不想去...)到stderr,但它不起作用:(当我尝试运行它时,它会冻结,好像其中一个进程(或两个进程)正在等待输入。是我的代码有问题吗?我也愿意接受其他方法的建议,只要最终结果有效。感谢您的帮助。
【问题讨论】:
标签: c pipe fork child-process