1. 通信原理
2. 通信步骤
1.先创建两个有名管道
2.打开有名管道
3.对有名管道进行读写操作
4.关闭管道
3. 代码实现
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#define BUF_SIZE 20
int main()
{
//mkfifoa
int ret = -1;
ret = mkfifo("fifoa",0666);
if(-1==ret&&EEXIST!=errno)
{
printf("mkfifoa error!\r\n");
return -1;
}
printf("create fifoa ok!\r\n");
//mkfifob
ret = mkfifo("fifob",0666);
if(-1==ret&&EEXIST!=errno)
{
return -1;
}
printf("create fifob ok!\r\n");
//open fifoa
int fdw = open("fifoa",O_WRONLY,0666);
if(-1==fdw)
{
printf("open error!\r\n");
return -1;
}
printf("2.open fifoa ok!\r\n");
//open fifob
int fdr = open("fifob",O_RDONLY,0666);
if(-1==fdr)
{
printf("open fifob error\r\n");
return -1;
}
//write read
char buf[BUF_SIZE] = {0};
while(1)
{
//write
memset(buf,0,BUF_SIZE);
printf("Please input:");
fgets(buf,BUF_SIZE,stdin);
write(fdw,buf,BUF_SIZE);
//read
memset(buf,0,BUF_SIZE);
read(fdr,buf,BUF_SIZE);
printf("b->a:%s\r\n",buf);
}
//close
close(fdw);
close(fdr);
return 0;
}
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#define BUF_SIZE 20
int main()
{
//open fifoa
int fdr = open("fifoa",O_RDONLY,0666);
if(-1==fdr)
{
printf("open fifoa error!\r\n");
return -1;
}
printf("2.open fifoa ok!\r\n");
//open fifob
int fdw = open("fifob",O_WRONLY,0666);
if(-1==fdw)
{
printf("open fifob error\r\n");
return -1;
}
//write read
char buf[BUF_SIZE] = {0};
while(1)
{
//read
memset(buf,0,BUF_SIZE);
read(fdr,buf,BUF_SIZE);
printf("a->b:%s\r\n",buf);
//write
memset(buf,0,BUF_SIZE);
printf("Please input:");
fgets(buf,BUF_SIZE,stdin);
write(fdw,buf,BUF_SIZE);
}
//close
close(fdw);
close(fdr);
return 0;
}
4. 效果展示