在一门类(class)中,老师给了我们一些代码(在粉笔板上),但他的字迹很糟糕,我无法拼出几个部分。管道和 fork 也是新的,所以这无济于事。
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
void main () {
int a[] = {1,2,3,4}, f[2]; // ok so we initialize an array and a "pipe folder" (pipefd in manual) ?
pipe (f); // not 100% sure what this does ?
if (fork () == 0) { // if child
close (f[0]); // close pipe read-end
a[0] += a[1];
write (f[1], &a[0], sizeof (int)) // fixed
close (f[1]); // close pipe write-end
exit(0); // closes child and sends status update to parent ?
}
else { // if parent
close (f[1]) // close write-end of pipe
a[2]+=a[3];
read (f[0], &a, sizeof(int)) // fixed
wait (0); // waits for child to ... close ? or just finish ? or is it the same thing
a[0]+= a[2]; close (f[0]);
printf ("%d\n, "a[0]);
}
}
child 和 parent 是否按某种特定顺序前进。我猜 parent 会等待 child 关闭,如果 close (f[1])
没有返回任何错误它会继续吗? (顺便说一下,wait(0)
中的“0”代表什么)然后才继续?
我误会了什么?我做对了吗?
我想我应该提到我使用 man
做了一些研究,但我发现它非常困惑。 就我而言,它们适用于已经知道自己在做什么但忘记了一些细节(比如要包含什么和 -p 做什么)的用户,或者只了解基本知识的用户。
最佳答案
pipe
创建两个文件描述符。一个是你写的,另一个是你读的。你写进一个,你可以从另一个读取。 UNIX 中的文件描述符是整数 (int
)。- 文件描述符由子进程继承。因此,管道使人们能够在进程之间进行通信。在这种情况下, child 写了一些数据,然后 parent 可以读取
- 不要在读/写中使用 8,而是使用
sizeof
即sizeof(int)
。编译将为存储的字节数和int
提供正确的值
wait(0)
等待子进程终止。
关于c - 管道/ fork 有问题。说明书看不懂一半(man),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10937600/