基本思路:
使用有名管道进行通信,
代码
chatA
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
int main(){
//判断管道文件是否存在
int ret = access("fifo1",F_OK);
if (ret == -1)
{
printf("管道不存在,创建对应的管道\n");
//创建管道
ret = mkfifo("fifo1",0664);
if(ret == -1){
perror("mkfifo");
exit(0);
}
}
ret = access("fifo2",F_OK);
if (ret == -1)
{
printf("管道不存在,创建对应的管道\n");
//创建管道
ret = mkfifo("fifo2",0664);
if(ret == -1){
perror("mkfifo");
exit(0);
}
}
//以只写的方式打开管道的FIFO1
int fdw = open("fifo1", O_WRONLY);
if (fdw == -1)
{
perror("open");
exit(0);
/* code */
}
printf("打开管道fifo1成功,等待写入.....\n");
int fdr = open("fifo2", O_RDONLY);
if (fdr == -1)
{
perror("open");
exit(0);
/* code */
}
printf("打开管道fifo2成功,等待读取.....\n");
//循环的去写读数据
char buf[128];
while (1)
{
memset(buf,0,128);
//获取表装输入的数据
fgets(buf,128,stdin);
//写数据
ret = write(fdw,buf,strlen(buf));
if (ret == -1)
{
perror("write");
exit(0);
/* code */
}
printf("buf :%s\n",buf);
// 读管道数据
memset(buf,0,128);
ret = read(fdr,buf,128);
if(ret <= 0){
perror("read");
break;
}
printf("buf :%s\n",buf);
}
// 关闭文件描述符
close(fdr);
close(fdw);
return 0;
}
chatB
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
int main()
{
//判断管道文件是否存在
int ret = access("fifo1",F_OK);
if (ret == -1)
{
printf("管道不存在,创建对应的管道\n");
//创建管道
ret = mkfifo("fifo1",0664);
if(ret == -1){
perror("mkfifo");
exit(0);
}
}
ret = access("fifo2",F_OK);
if (ret == -1)
{
printf("管道不存在,创建对应的管道\n");
//创建管道
ret = mkfifo("fifo2",0664);
if(ret == -1){
perror("mkfifo");
exit(0);
}
}
//以只读的方式打开管道的FIFO1
int fdr = open("fifo1", O_RDONLY);
if (fdr == -1)
{
perror("open");
exit(0);
/* code */
}
printf("打开管道fifo1成功,等待读入.....\n");
int fdw = open("fifo2", O_WRONLY);
if (fdw == -1)
{
perror("open");
exit(0);
/* code */
}
printf("打开管道fifo2成功,等待写入....\n");
//循环的去读写数据
char buf[128];
while (1)
{
// 读管道数据
memset(buf,0,128);
ret = read(fdr,buf,128);
if(ret <= 0){
perror("read");
break;
}
printf("buf :%s\n",buf);
memset(buf,0,128);
//获取表装输入的数据
fgets(buf,128,stdin);
//写数据
ret = write(fdw,buf,strlen(buf));
if (ret == -1)
{
perror("write");
exit(0);
/* code */
}
printf("buf :%s\n",buf);
}
// 关闭文件描述符
close(fdr);
close(fdw);
return 0;
}
缺点:读和写不能同时进行