在 C 中使用管道在 parent 和 child 之间创建双向通信

Create 2-way communication between parent and child using pipes in C

我正在尝试编写一个程序,允许进程与其 child 进行双向通信,即它可以向 child 发送消息,也可以从 child 接收消息。我第一次尝试创建 2 个管道和 link 管道的每一端到 parent 和 child stdin 和 stdout:

#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;
}

该程序应该从 child 向 parent 发送消息,然后 parent 向 child 发送回复,然后 child 将最终结果(斯塔克先生……我感觉不太好……我不想去……)打印到标准错误,但它不起作用:(当我尝试 运行 它,它冻结,好像其中一个进程(或两个进程)正在等待输入。我的代码有问题吗?我也愿意接受其他方法的建议,只要最终结果有效。感谢您的帮助。

fgets 读取直到看到换行符(或缓冲区已满)。

parent 开头为

fgets(message, 70, stdin);

正在等待中。

child 输出

printf("Mr. Stark...");

然后也等待:

fgets(input, 70, stdin);

"Mr. Stark..." 不包含换行符。事实上,它可能根本没有被发送,而是在 stdout 中缓冲,但这可以在 printf.

之后用 fflush(stdout) 修复

但即便如此,fgets 仍会等待永远不会出现的换行符。

修复:

printf("Mr. Stark...\n");
fflush(stdout);