c - 使用 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
我做错了什么?
解决方案
输出可能不会立即写入,printf
但会延迟到缓冲区已满,因为默认情况下printf
,其他函数stdio.h
使用缓冲输出。
尝试以下方法之一:
- 在禁用缓冲
setbuf(stdout, NULL);
之前添加或fork()
fflush(stdout)
在printf
或之后使用- 使用
write
而不是printf
.
推荐阅读
- ios - popover allowedArrowDirections = .left/.right 与 popover 框架混淆
- tensorflow - Failed call to cuInit: CUDA_ERROR_NOT_INITILIZED: initialization error when I execute codes in Jupyter notebook , and the GPU isn't being used
- ios - 如何在推送通知中获取数据?
- python - 使用 doc2vec 和 gensim 的文本分类模型
- python - 用相同的字符串和随机后缀替换字符串
- react-native - ReactNative - Using FlatList and redux to update is slow
- c# - Click not working on a button that is dynamically created in C#
- tsql - 动作方法返回null
- python - 自我没有定义?
- ios - 为什么 iOS 11.4 无法获取设备令牌值和 FCM 令牌值?