【发布时间】:2017-01-31 00:21:59
【问题描述】:
我正在尝试理解管道。该程序运行良好(父母向其孩子发送消息“你好”,孩子打印它。我不明白两件事:
程序是否会在某个时候停止,因为假设子进程关闭了写描述符,同时父进程也关闭了写描述符?
为什么描述符关闭后不需要再打开?
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main(){
int desc[2];
pipe(desc);
int pid = fork();
if(pid == 0){
while(1){
char buffer[100];
close(desc[1]);
read(desc[0], buffer, 100);
printf("Child: recieved message - '%s'\n", buffer);
}
}
if(pid > 0){
while(1){
sleep(1);
char buffer[100];
strcpy(buffer, "Hello, child!");
close(desc[0]);
write(desc[1], buffer, 100);
}
}
return 0;
}
【问题讨论】: