基于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;
}
结果:
先打开读端,再打开写端,然后看到读端的代码如下: