libevent 01

read fifo using libevent.

#include <stdio.h>                                                                    
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <event.h>
#include <fcntl.h>
/*
   当监听的事件满足条件的时候,会触发回调函数,通过回调函数读取数据
 */
void fifo_read(evutil_socket_t fd, short events, void *arg) {
    char buf[32] = {0};
    int ret = read(fd, buf, sizeof(buf));
    if (-1 == ret) {
        perror("read");
        exit(1);
    }   

    printf("从管道读取: %s\n", buf);
}

int main() {
    int ret = mkfifo("fifo.tmp", 00700);
    if (-1 == ret) {
        perror("mkfifo");
        exit(1);
    }

    int fd = open("fifo.tmp", O_RDONLY);
    if (-1 == fd) {
        perror("open");
        exit(1);
    }
    
    // 创建事件
    struct event ev;

    // 初始化事件集合
    event_init();

    // 初始化事件(把fd和事件ev绑定)
    // 参数:事件、关联的文件描述符、事件类型、回调函数、回调函数参数
    event_set(&ev, fd, EV_READ | EV_PERSIST, fifo_read, NULL);

    //把事件添加到集合
    event_add(&ev, NULL);

    //开始监吿
    event_dispatch();  //死循玿 如果集合中没有事件可以监听,则返囿
    
    exit(0);
} 

write fifo:

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

int main()
{
    int fd = open("fifo.tmp", O_WRONLY);
    if (-1 == fd) 
    {
        perror("open");
        exit(2);
    }   

    char *buf = "1234\n";

    while (1)
    {
        if (write(fd, buf, strlen(buf)) == -1)
        {
            perror("write");
            break;
        }
        sleep(1);
    }
    close(fd);
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值