使用有名管道实现两个进程之间相互通信,提示:可以使用多线程或多进程实现
creat.c
#include<head.h>
int main(int argc, const char *argv[])
{
//创建有名管道
if(mkfifo("./myfifo", 0664) != 0)
{
perror("mkfifo error");
return -1;
}
//getchar(); //阻塞程序
//system("rm myfifo");
if(mkfifo("./myfifo1",0664)!=0)
{
perror("mkfifo");
return -1;
}
//getchar();
//system("rm myfifo1");
return 0;
}
write.c
#include<head.h>
int main(int argc, const char *argv[])
{
pid_t wp=fork();
//打开管道文件
//循环向文件中写入数据
if(wp>0)
{
int wfd;
if((wfd = open("./myfifo", O_WRONLY)) == -1)
{
perror("open error");
return -1;
}
char buf[128] = "";
while(1)
{
bzero(buf, sizeof(buf)); //清空
// printf("A请输入>>:");
fgets(buf, sizeof(buf), stdin); //从终端获取数据
buf[strlen(buf)-1] = 0; //将换行换成'\0'
//将数据写入管道文件中
write(wfd, buf, sizeof(buf));
//如果输入的是quit,则退出进程
if(strcmp(buf, "quit") == 0)
{
printf("A写进程退出\n");
break;
}
}
close(wfd);
}
else if(wp==0)
{
int rfd;
if((rfd=open("./myfifo1",O_RDONLY))==-1)
{
perror("open");
return -1;
}
char buf[128] = "";
while(1)
{
bzero(buf, sizeof(buf)); //清空
//从管道中读取数据
read(rfd, buf, sizeof(buf));
if(strcmp(buf, "quit") == 0)
{
printf("B写进程已经退出,A读进程也要退出了\n");
break;
}
//将数据展示到终端
printf("A读取的数据:%s\n", buf);
}
exit(0);
close(rfd);
}
else
{
perror("fork");
return -1;
}
return 0;
}
read.c
#include<head.h>
int main(int argc, const char *argv[])
{
pid_t rp=fork();
//打开有名管道文件
//从有名管道中读取数据
if(rp>0)
{
int wfd;
if((wfd=open("./myfifo1",O_WRONLY))==-1)
{
perror("open");
return -1;
}
char buf[128] = "";
while(1)
{
bzero(buf, sizeof(buf)); //清空
// printf("B请输入>>:");
fgets(buf, sizeof(buf), stdin); //从终端获取数据
buf[strlen(buf)-1] = 0; //将换行换成'\0'
//将数据写入管道文件中
write(wfd, buf, sizeof(buf));
//如果输入的是quit,则退出进程
if(strcmp(buf, "quit") == 0)
{
printf("B写进程退出\n");
break;
}
}
close(wfd);
}
else if(rp==0)
{
int rfd;
if((rfd = open("./myfifo", O_RDONLY)) ==-1)
{
perror("open error");
return -1;
}
char buf[128] = "";
while(1)
{
bzero(buf, sizeof(buf)); //清空
//从管道中读取数据
read(rfd, buf, sizeof(buf));
if(strcmp(buf, "quit") == 0)
{
printf("A写进程已经退出,B读进程也要退出了\n");
break;
}
//将数据展示到终端
printf("B读取的数据:%s\n", buf);
}
exit(0);
close(rfd);
}
else
{
perror("fork");
return -1;
}
return 0;
}