【发布时间】:2017-09-02 19:15:02
【问题描述】:
我正在尝试将值从子级发送给父级,但没有得到所需的输出。谁能弄清楚我做错了什么?
int main() {
printf("I am the parent with process ID:%d\r\n", (int) getpid());
int rc = fork();
int sum = 0;
int array[6] = {2, 3, 7, -1, 10, 6};
int pipeNum[2];
pipe(pipeNum);
if (rc < 0) {
fprintf(stderr, "fork failed\r\n");
exit(1);
} else if (rc == 0) {
for (int i = 0; i < 6; i++) {
sum += array[i];
}
close(pipeNum[0]);
printf("I am the child with process ID:%d and I am sending %d to my parent.\r\n", (int) getpid(), sum);
write(pipeNum[1], &sum, sizeof(sum));
close(pipeNum[1]);
} else {
wait(NULL);
close(pipeNum[1]);
read(pipeNum[0], &sum, sizeof(sum));
printf("I am the parent with process ID:%d with a final sum of %d\r\n", (int) getpid(), sum);
close(pipeNum[0]);
exit(0);
}
return 0;
}
这是我得到的输出
我是进程 ID 的父级:XXX
我是进程 ID:XXX 的孩子,我将 27 发送给我的父母。
我是进程 ID:XXX 的父级,最终总和为 0
任何帮助将不胜感激
【问题讨论】: