使用有名管道完成两个进程之间相互通信
#include<myhead.h>
int main(int argc, const char *argv[])
{
//创建有名管道文件1
if(mkfifo("./myfifo1",0664) !=0 )
{
perror("myfifo1 error");
return -1;
}
//创建有名管道文件2
if(mkfifo("./myfifo2",0664) !=0 )
{
perror("myfifo2 error");
return -1;
}
printf("文件创建成功\n");
//使用getchar阻塞
getchar();
system("rm myfifo1 myfifo2");
return 0;
}
#include<myhead.h>
int main(int argc, const char *argv[])
{
pid_t pid;
pid=fork();
if(pid>0)
{
//以只写的形式打开管道文件1
int wfd = -1;
if((wfd = open("./myfifo1", O_WRONLY)) == -1)
{
perror("open error");
return -1;
}
//向管道文件1中循环写入数据
char wbuf[128]="";
while(1)
{
//清空内容
bzero(wbuf, sizeof(wbuf));
//从终端输入数据
printf("请输入:\n");
//刷新缓存区
fflush(stdout);
//从终端读取数据
read(0, wbuf, sizeof(wbuf));
wbuf[strlen(wbuf)-1] = '\0';
write(wfd, wbuf, sizeof(wbuf));
if(strcmp(wbuf,"quit") == 0)
break;
}
}
else if(pid==0)
{
//以只读的形式打开管道文件2
int rfd = -1;
if((rfd = open("./myfifo2", O_RDONLY)) == -1)
{
perror("open error");
return -1;
}
//向管道文件2中循环写入数据
char rbuf[128]="";
while(1)
{
//清空内容
bzero(rbuf, sizeof(rbuf));
//从管道2中读取数据
read(rfd, rbuf, sizeof(rbuf));
printf("收到消息:%s\n",rbuf);
//判断结束
if(strcmp(rbuf,"quit") == 0)
break;
}
exit(EXIT_SUCCESS);
}
wait(NULL);
return 0;
}
#include<myhead.h>
int main(int argc, const char *argv[])
{
pid_t pid;
pid=fork();
if(pid>0)
{
//以只读的形式打开管道文件1
int rfd = -1;
if((rfd = open("./myfifo1", O_RDONLY)) == -1)
{
perror("open error");
return -1;
}
//向管道文件1中循环写入数据
char rbuf[128]="";
while(1)
{
//清空内容
bzero(rbuf, sizeof(rbuf));
//从管道1中读取数据
read(rfd, rbuf, sizeof(rbuf));
printf("收到消息:%s\n",rbuf);
//判断结束
if(strcmp(rbuf,"quit") == 0)
break;
}
}
else if(pid==0)
{
//以只写的形式打开管道文件2
int wfd = -1;
if((wfd = open("./myfifo2", O_WRONLY)) == -1)
{
perror("open error");
return -1;
}
//向管道文件2中循环写入数据
char wbuf[128]="";
while(1)
{
//清空内容
bzero(wbuf, sizeof(wbuf));
//从终端输入数据
printf("请输入:\n");
//刷新缓存区
fflush(stdout);
//从终端读取数据
read(0, wbuf, sizeof(wbuf));
wbuf[strlen(wbuf)-1] = '\0';
write(wfd, wbuf, sizeof(wbuf));
if(strcmp(wbuf,"quit") == 0)
break;
}
exit(EXIT_SUCCESS);
}
wait(NULL);
return 0;
}