首页 > 解决方案 > 使用 2 个管道进行进程同步

问题描述

我在做作业。我需要用一个孩子编写一个 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);
        }
    }

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

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

我做错了什么?

标签: coperating-systempipe

解决方案


输出可能不会立即写入,printf但会延迟到缓冲区已满,因为默认情况下printf,其他函数stdio.h使用缓冲输出。

尝试以下方法之一:

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

推荐阅读