【问题标题】:Unix dup pipes after forkfork 后的 Unix dup 管道
【发布时间】:2013-11-06 11:49:57
【问题描述】:

我想使用管道实现子进程和它的父进程之间的通信。代码如下:

#include <stdio.h>
int main() {
    int pipe_dsc[2];
    if (pipe(pipe_dsc) == -1) {
        printf("error\n");
    }
    switch (fork()) {
        case -1:
            printf("error\n");
            return 0;
        case 0: //children
            close(0);
            dup(pipe_dsc[0]);

            close(pipe_dsc[1]);

            int x;
            scanf("%d", &x);

            printf("succes: %d\n", x);
            return 0;

        default: //parent
            close(1);
            dup(pipe_dsc[1]);

            close(pipe_dsc[0]);
            printf("127");

            wait(0);
            return 0;
    }
    return 0;
}

父母应该写一个数字 127,孩子应该读它,但它没有。孩子一直在 scanf 等待。怎么了?

【问题讨论】:

  • 您知道,“children”是复数形式。单数形式是“child”。

标签: c unix fork pipe dup


【解决方案1】:

我想冲洗可能会有所帮助:

fflush(stdout);

但在我的测试中,我通过在字符串中添加\n 取得了成功。我猜sscanf 不会以“未完成”的字符串开头。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    • 2011-01-26
    • 1970-01-01
    • 1970-01-01
    • 2011-07-02
    • 2011-10-08
    相关资源
    最近更新 更多