libevent实现对管道的读写操作

读管道:

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

//对操作的处理函数
void read_cb(evutil_socket_t fd, short what, void *arg)
{
    //读管道
    char buf[1024] = {0};
    int len = read(fd, buf, sizeof(buf));
    printf("read event: %s \n ", what & EV_READ ? "YES":"NO");
    printf("data len = %d, buf = %s\n", len, buf);
    sleep(1);
}

int main(int argc, const char* argv[])
{
    unlink("myfifo");
    
    //创建有名管道
    mkfifo("myfifo", 0664);
    
    //open file
    int fd = open("myfifo", O_RDONLY | O_NONBLOCK);
    if(fd == -1)
    {
        printf("open error");
        exit(1);
    }
    
    //创建一个event_base
    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);
    
    //添加事件
    event_add(ev, NULL);
    
    //事件循环
    event_base_dispatch(base);
    
    //释放资源
    event_free(ev);
    event_base_free(base);
    close(fd);
}

写管道:

//读管道
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
#include <event2/event.h>

//对操作的处理函数
void write_cb(evutil_socket_t fd, short what, void *arg)
{
    //写管道
    char buf[1024] = {0};
    static int num = 0;
    sprintf(buf, "hello world-%d\n", num++);
    write(fd, buf, strlen(buf) +1);
    sleep(1);
}

int main(int argc, const char* argv[])
{
    //open file
    int fd = open("myfifo", O_WRONLY | O_NONBLOCK);
    if(fd == -1)
    {
        printf("open error");
        exit(1);
    }
    
    //创建一个event_base
    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);
    
    //添加事件
    event_add(ev, NULL);
    
    //事件循环
    event_base_dispatch(base);
    
    //释放资源
    event_free(ev);
    event_base_free(base);
    close(fd);
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农code之路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值