编写程序实现以下功能:
利用匿名管道实现父子进程间通信,要求父进程发送字符串“hello child”给子进程;
子进程收到父进程发送的数据后,给父进程回复“hello farther”
父子进程通信完毕,父进程依次打印子进程的退出状态以及子进程的pid。
管道作为较为原始的进程间的通信方式,在进程间的通信中被广泛使用。管道可分为有名管道和匿名管道,两者有相似之处又有一定的区别。
匿名管道的特点如下:
1.匿名管道是半双工的,数据只能朝一个放向流动,因此要实现两个进程的通信,就必须建立两个匿名管道;
2.匿名管道只能在管道尾部写入数据,从管道头部读取数据;fd[0]用于进程读取数据,fd[1]用于进程写入数据;
3.匿名管道不具备存储数据的能力,数据一旦被读取,其它进程将不能从该管道中读取数据;
4.匿名管道只能在有血缘关系的进程间通信;如父子进程和兄弟进程。
程序如下:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
int fd1[2],fd2[2];
pipe(fd1);
pipe(fd2);
int pid;
pid = fork();
if(pid < 0)
perror("fork");
else if(pid == 0)
{
close(fd1[0]);
close(fd2[1]);
char str[12];
printf("This is the child!\n");
if(read(fd2[0],str,12) > 0)
{
printf("Received the news: %s\n",str);
if(write(fd1[1],"hello father",12) < 0)
perror("write");
}
else
perror("read");
exit(5);
}
else
{
int status;
printf("This is the father!\n");
close(fd1[1]);
close(fd2[0]);
char buf[24] = "hello child";
if(write(fd2[1],buf,12) < 0)
perror("write");
else
{
printf("Send news successful!\n");
}
wait(&status);
if(WIFEXITED(status))
{
printf("The child's pid is: %d\n",pid);
printf("The child's exited status is: %d\n",WEXITSTATUS(status));
}
}
return 0;
}
程序结果: