在一门课程中,老师给了我们一些代码(在粉笔板上),但是他手写的很糟糕,而且我不能做出一些部分.管道和叉子也是新的,所以没有帮助.
#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]);
}
}
Run Code Online (Sandbox Code Playgroud)
孩子和父母是否按某种特定顺序行事.我猜父母等待孩子关闭,如果close (f[1])没有错误就继续吗?(顺便说一句"0"代表什么wait(0))然后才继续?
我有什么误会?我能做对吗?
我想我应该提一下,我做了一些研究,man但我发现它非常令人困惑.就我而言,它们适用于那些已经知道自己在做什么但却忘记了一些细节(比如要包含什么和-p做什么)或者有更多基本理解的人的用户.
pipe创建两个文件描述符.你写的一个,你读的另一个.你写的是什么,你可以从另一个读.UNIX中的文件描述符是整数(int).sizeofie sizeof(int).编译将为存储的字节数提供正确的值intwait(0) 等待孩子终止.| 归档时间: |
|
| 查看次数: |
558 次 |
| 最近记录: |