目录
1.题目
无名管道实现进程通信
2.分析
无名管道进程通信,只能用于父子进程
3.代码运行
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <glob.h>
#include <signal.h>
#include <string.h>
#if 0
无名管道只能用于父子进程,具有血缘关系
#endif
int main(int argc,char *argv[])
{
int fd[2]={0};
int pi=pipe(fd);//创建无名管道
if(pi<0)
{
perror("pipe");
return -1;
}
printf("无名管道文件创建成功 p \n");
pid_t pid=fork();
if(pid == 0)//子进程写消息
{
char buf[12]={0};
close(fd[0]);//关闭读端
while(1)
{
scanf("%s",buf);
write(fd[1],buf,sizeof(buf));
if(strcmp(buf,"quit")==0)//进行退出,根据quit字符串
break;
}
exit(0);
}else if(pid>0)//父进程读消息
{
char buf1[12]={0};
close(fd[1]);//关闭写端
while(1)
{
read(fd[0],buf1,sizeof(buf1));
if(strcmp(buf1,"quit")==0)
break;
printf("buf1:%s\n",buf1);
}
}
return 0;
}