【发布时间】:2017-01-04 20:44:16
【问题描述】:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, char **argv) {
int childs[3];
for (int i = 0; i < 3; ++i) {
int p[2];
if (pipe(p) == -1) { perror("pipe"); exit(1); }
pid_t pid = fork();
if (pid) {
close(p[0]);
childs[i] = p[1];
}
else {
close(p[1]);
printf("child %d start\n", i + 1);
char buf[10];
buf[0] = 0;
int r;
if ((r = read(p[0], buf, 9)) == -1) { ... }
printf("child %d read %s (%d), finish\n", i + 1, buf, r);
sleep(2);
exit(0);
}
}
for (int i = 0; i < 3; ++i) {
// if (argc > 1) {
// write(childs[i], "42", 2);
// }
// ============== HERE >>>
close(childs[i]);
}
pid_t pid;
while ((pid = waitpid(-1, NULL, 0)) > 0) {
printf("child %d exited\n", pid);
}
return 0;
}
带有注释的输出:
child 1 start
child 2 start
child 3 start
child 3 read (0), finish
2秒后显示下一行
child 2 read (0), finish
2秒后显示下一行
child 1 read (0), finish
我不写到父频道。关闭它,我想向将在read 中等待的孩子发出信号。
好像有以下的。 Сhild N 预期完成读取结果 0,没关系。孩子2 (N-1) 和1 被锁定在一个read 到一个孩子3 完成。那么1的孩子类似会等。
为什么会发生锁?
【问题讨论】:
标签: c unix ipc system-calls