当前位置: 首页 > news >正文

Linux:基于libevent读写管道代码

基于libevent读写管道代码:

读端:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <event2/event.h>
#include <event2/bufferevent.h>
#include <event2/listener.h>
#include <fcntl.h>

void read_cb(evutil_socket_t fd, short what, void* arg) {
//把管道中的数据读出到buf中,然后打印出来
char buf[1024] = {0};
int len = read(fd,buf,sizeof(buf));
printf(“data len= %d , buf= %s\n”,len,buf);
printf(“read event: %s\n”, what & EV_READ ? “YES” : “NO”);
}

int main(int argc, const char* argv[])
{
//先删除同名管道,再创建管道
unlink(“myfifo”);
mkfifo(“myfifo”, 0664);

int fd = open("myfifo", O_RDONLY | O_NONBLOCK);
if(-1 == fd) {perror("create fifo pipe fail");exit(1);
}//创建事件框架,事件的根结点
struct event_base* base = NULL;
base = event_base_new();//创建事件
struct event* ev = NULL;
ev = event_new(base, fd, EV_READ | EV_PERSIST, read_cb, NULL);//往事件框架中添加事件ev
event_add(ev,NULL);//分发事件
event_base_dispatch(base);//释放资源
event_free(ev);
event_base_free(base);
close(fd);
return 0;

}

写端:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <event2/event.h>
#include <event2/bufferevent.h>
#include <event2/listener.h>
#include <fcntl.h>

void write_cb(evutil_socket_t fd, short what, void* arg) {
//把数据写到buf中,然后写到管道中,然后打印出来
char buf[1023] = {0};
static int num = 0;
sprintf(buf, “hello world == %d \n”, num++);
write(fd, buf, strlen(buf)+1);

}

int main(int argc, const char* argv[])
{
//管道已经在read_fifo.c中创建管道

int fd = open("myfifo", O_WRONLY | O_NONBLOCK);
if(-1 == fd) {perror("create fifo pipe fail");exit(1);
}//创建事件框架,事件的根结点
struct event_base* base = NULL;
base = event_base_new();//创建事件
struct event* ev = NULL;
ev = event_new(base, fd, EV_WRITE | EV_PERSIST, write_cb, NULL);//往事件框架中添加事件ev
event_add(ev,NULL);//分发事件
event_base_dispatch(base);//释放资源
event_free(ev);
event_base_free(base);
close(fd);
return 0;

}

结果:

先打开读端,再打开写端,然后看到读端的代码如下:
guand

http://www.lryc.cn/news/16576.html

相关文章:

  • 2022年中职网络安全逆向题目整理合集
  • Tencent OS下逻辑卷(LVM)增加硬盘扩容
  • 【Java】Spring的创建和使用
  • 【HTML】HTML 表单 ④ ( textarea 文本域控件 | select 下拉列表控件 )
  • MySQL 操作 JSON 数据类型
  • 关于vue3生命周期的使用、了解以及用途(详细版)
  • 2月,真的不要跳槽。
  • Vulnhub靶场----4、DC-4
  • 51单片机学习笔记_12 LCD1602 原理及其模块化代码
  • 科技 “新贵”ChatGPT 缘何 “昙花一现” ,仅低代码风靡至今
  • redis基本入门| 怎么安装redis?什么的是redis?怎么使用?
  • kubernetes traefik ingress 安装部署以及使用和注意点
  • 电脑病毒已灭绝,是真的吗?
  • 基于RK3399+Linux QT地面测试台多参数记录仪测试平台软件设计(二)
  • 追梦之旅【数据结构篇】——详解C语言实现动态版顺序栈
  • Ubuntu 使用Nohup 部署/启动/关闭程序
  • Spring 用到了哪些设计模式
  • Linux上基于PID找到对应的进程名以及所在目录
  • jvm知识点与面试题
  • 算法前缀和—Java版
  • 拨开迷雾 看见vivo穿越周期的秘密
  • 浅谈常用的日志框架
  • 字节是真的难进,测开4面终上岸,压抑5个月,终于可以放声呐喊
  • Bash初识
  • ElasticSearch Script 操作数据最详细介绍
  • 【黑盒模糊测试】路由器固件漏洞挖掘实战--AFL++ qemu_mode
  • 【java实现Word模板导出】Xdocreport和Freemaker
  • Stable-Baselines 3 部分源代码解读 3 ppo.py
  • [业务逻辑] 订单超时怎么处理
  • iOS上架及证书最新创建流程