Linux多进程10-有名管道实现简单版聊天功能
chatA.c
//有名管道实现简单版聊天功能
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
int main(int argc, char const *argv[])
{
//判断有名管道文件是否存在
int ret = access("fifo1", F_OK);
if (ret == -1)
{
//文件不存在
printf("管道不存在,创建对应的有名管道\n");
ret = mkfifo("fifo1", 0664);
if (ret == -1)
{
perror("mkfifo err");
exit(0);
}
}
ret = access("fifo2", F_OK);
if (ret == -1)
{
//文件不存在
printf("管道不存在,创建对应的有名管道\n");
ret = mkfifo("fifo2", 0664);
if (ret == -1)
{
perror("mkfifo err");
exit(0);
}
}
//以只写的方式打开管道fifo1
int fdw = open("fifo1", O_WRONLY);
if (fdw == -1)
{
perror("open err");
exit(0);
}
printf("打开fifo1成功,等待写入数据\n");
//以只读的方式打开管道fifo1
int fdr = open("fifo2", O_RDONLY);
if (fdr == -1)
{
perror("open err");
exit(0);
}
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 err");
exit(0);
}
//读数据
memset(buf, 0, 128);
ret = read(fdr, buf, 128);
if (ret <= 0)
{
perror("read err");
break;
}
printf("buf: %s\n", buf);
}
close(fdw);
close(fdr);
return 0;
}
chatB.c
//有名管道实现简单版聊天功能
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
int main(int argc, char const *argv[])
{
//判断有名管道文件是否存在
int ret = access("fifo1", F_OK);
if (ret == -1)
{
//文件不存在
printf("管道不存在,创建对应的有名管道\n");
ret = mkfifo("fifo1", 0664);
if (ret == -1)
{
perror("mkfifo err");
exit(0);
}
}
ret = access("fifo2", F_OK);
if (ret == -1)
{
//文件不存在
printf("管道不存在,创建对应的有名管道\n");
ret = mkfifo("fifo2", 0664);
if (ret == -1)
{
perror("mkfifo err");
exit(0);
}
}
//以只读的方式打开管道fifo1
int fdr = open("fifo1", O_RDONLY);
if (fdr == -1)
{
perror("open err");
exit(0);
}
printf("打开fifo1成功,等待读取数据\n");
//以只读的方式打开管道fifo1
int fdw = open("fifo2", O_WRONLY);
if (fdw == -1)
{
perror("open err");
exit(0);
}
printf("打开fifo2成功,等待写入数据\n");
char buf[128];
//循环读写数据
while (1)
{
//读数据
memset(buf, 0, 128);
ret = read(fdr, buf, 128);
if (ret <= 0)
{
perror("read err");
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 err");
exit(0);
}
}
close(fdw);
close(fdr);
return 0;
}
本文作者:言叶以上
本文链接:https://www.cnblogs.com/anqwjoe/p/17409735.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
分类:
Linux
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
2018-05-17 Vue.js 基础知识