【发布时间】: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