【问题标题】:process synchronization with 2 pipes使用 2 个管道进行进程同步
【发布时间】:2019-05-07 08:00:56
【问题描述】:

我正在做作业。我需要用一个孩子编写一个 C 程序,然后父亲和孩子必须为每个孩子打印到标准输出一行。 基本上我想要这样的东西:

I'm the father
I'm the child
I'm the father
I'm the child
I'm the father
I'm the child
...

我只能使用两个管道进行进程通信。 这是我写的:

int par_read = pipe1[0];
int par_write = pipe2[1];
int cld_read = pipe2[0];
int cld_write = pipe1[1];

char w;

if (fork()) // par
{
    close(cld_read);
    close(cld_write);

    while(1)
    {
        printf("I'm the father\n");

        if (write(par_write, &w, 1) == -1)
        {
            fprintf(stderr, "Error on par_write: %s\n", strerror(errno));
            exit(EXIT_FAILURE);
        }

        if (read(par_read, &w, 1) == -1)
        {
            fprintf(stderr, "Error on par_read: %s\n", strerror(errno));
            exit(EXIT_FAILURE);
        }
    }

}
else    // cld
{
    close(par_read);
    close(par_write);

    while(1)
    {
        if (read(cld_read, &w, 1) == -1)
        {
            fprintf(stderr, "Error on cld_read: %s\n", strerror(errno));
            exit(EXIT_FAILURE);
        }

        printf("I'm the child\n");

        if (write(cld_write, &w, 1) == -1)
        {
            fprintf(stderr, "Error on cld_write: %s\n", strerror(errno));
            exit(EXIT_FAILURE);
        }
    }

完整代码here。 问题是这两个进程只有在几百行之后才开始正常工作。第一行充满了“我是父亲”。我还检查了它的行数:

$ ./ex > ex_out
$ cat ex_out | wc -l
40960
$ cat ex_out | uniq | wc - l
255

我做错了什么?

【问题讨论】:

    标签: c operating-system pipe


    【解决方案1】:

    printf 输出可能不会立即写入,而是会延迟到缓冲区已满,因为 printfstdio.h 的其他函数默认使用缓冲输出。

    尝试以下方法之一:

    • fork() 之前添加setbuf(stdout, NULL); 以禁用缓冲或
    • printf 之后使用fflush(stdout)
    • 使用write 而不是printf

    【讨论】:

    • 实际上,输出到stdoutline“默认”缓冲的,但是当连接到管道时,它是完全缓冲的。
    猜你喜欢
    • 2018-04-23
    • 1970-01-01
    • 1970-01-01
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多