【发布时间】:2015-04-17 07:13:43
【问题描述】:
我正在尝试使用管道从父母向孩子发送两条消息“hello World”和“Goodbye”。孩子收到消息后必须打印出来。 我的问题是如何发送第二条消息。我编译并运行程序,但它只打印第一条消息。有什么建议吗? 这是我的代码:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 50
void main(){
int fd[2], n, status;
char buf[MAX];
pid_t pid;
char str1[]="Hello World!\n";
char str2[]="Goodbye\n";
pipe(fd);
if((pid=fork())<0){
abort();
}
else if(pid>0){// parent code goes here
close (fd[0]); // close read channel of parent
/*Send "hello world" through the pipe*/
write(fd[1],str1,(strlen(str1))); // write to the pipe
wait(&status);
close(fd[0]);
write(fd[1],str2,(strlen(str2)));
}
else{ // child code goes here
close(fd[1]); // close write channel of child
n=read(fd[0], buf, sizeof(buf)); // reads from the pipe
write(STDOUT_FILENO, buf, n);
exit(0);
}
}
【问题讨论】:
-
为什么要在父级中关闭
fd[0]两次? -
wait等待子进程退出。为什么你在孩子完成后尝试向管道写一些东西并且不会尝试读取它? -
第二次关闭没有意义,你是对的。我的错误我试图等待孩子结束在管道上再次写,但我真的不知道这是否正确。 ://
-
建议在编译时启用所有警告。然后 'void main()' 将被更正为 'int main(void)' 并包含头文件 'sys/types.h' 以便定义 'pid_t'。
-
关于行:'wait(&status)' 等待子退出,同时捕获退出状态/值。可能不是你想做的。为什么代码关闭 fd[0] 不止一次? “管道”不知道 EOF、记录或任何格式。读取管道的代码需要考虑到这一点,