//读代码的一个工具:UltraEdit了解一下
fifo读写通讯的实现
① read_fifo👇
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<errno.h>
#include<sys/types.h>
#include<fcntl.h>
#include<event2/event.h>
#include<sys/stat.h>
void sys_err(const char *str)
{
perror(str);
exit(1);
}
//typedef void(*event_callback)(evutil_socket_t fd, short, void*);
//读回调
void read_cb(evutil_socket_t fd, short what, void* arg)
{
char buf[BUFSIZ];
int len = read(fd, buf, sizeof(buf));
printf("what = %s, read from write: %s\n", what &EV_READ ? "read yes" : "read no", buf);
sleep(1);
return;
}
int mian(int argc, char *argv[])
{
//创建fifo
unlink("testfifo");//先检查要创建的管道是否存在,存在的话就先删掉
mkfifo("testfifo", 0664);//#include<sys/stat.h>
//打开fifo的读端
int fd = open("testfifo", O_RDONLY | O_NONBLOCK);//#include<fcntl.h>
if(fd == -1)
{
sys_err("open err");
}
//原本打开成功之后就可以去读了,但是现在想要libevent库设置读监听事件,一旦满足就自动回调
//创建event_base
struct event_base *base = event_base_new();
//创建事件
struct event *ev = NULL;
ev = event_new(base, fd, EV_READ|EV_PERSIST, read_cb, NULL);//#include<event2/event.h>
//添加事件到event_base
int event_add(ev, NULL);
//启动循环 int event_base_dispatch(strcut event_base *base);
event_base_dispatch(base);//相当于while(1){epoll}
//销毁event_base
event_base_free(base);
return 0;
}
② writefifo👇
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<errno.h>
#include<pthread.h>
#include<fcntl.h>
#include<event2/event.h>
#include<sys/stat.h>
void sys_err(const char *str)
{
perror(str);
exit(1);
}
//typedef void(*event_callback)(evutil_socket_t fd, short, void*);
//读回调
void write_cb(evutil_socket_t fd, short what, void* arg)
{
//char buf[BUFSIZ];
char buf[] = "hello libevent";
write(fd, buf, strlen(buf)+1);
sleep(1);
return;
}
int mian(int argc, char *argv[])
{
//打开fifo的写端
int fd = open("testfifo", O_WRONLY | O_NONBLOCK);//#include<fcntl.h>
if(fd == -1)
{
sys_err("open err");
}
//原本打开成功之后就可以去读了,但是现在想要libevent库设置读监听事件,一旦满足就自动回调
//创建event_base
struct event_base *base = event_base_new();
//创建事件对象
struct event *ev = NULL;
ev = event_new(base, fd, EV_WRITE|EV_PERSIST, write_cb, NULL);//#include<event2/event.h>
//添加事件到event_base
int event_add(ev, NULL);
//启动循环 int event_base_dispatch(strcut event_base *base);
event_base_dispatch(base);//相当于while(1){epoll}
//销毁event_base
event_base_free(base);
return 0;
}
未决和非未决
未决:有资格被处理,但还没有被处理
非未决:没有资格被处理