创建一个事件处理框架并显示系统中可以用那些io转接函数,以及现在使用的是哪种,并消除该事件
#include <iostream>
#include <event2/event.h>
using namespace std;
int main()
{
struct event_base* base = NULL;
base = event_base_new();//创建新的事件框架
const char** meths = event_get_supported_methods();//显示系统中可以使用哪些io转接函数
for (int i=0; meths[i] != NULL; ++i)
{
cout<<meths[i];
}
cout<<"\ncurrent = "<<event_base_get_method(base);//显示当前使用的是哪一种转接函数
event_base_free(base);//释放事件框架
return 0;
}
用libevent库写有名管道通信
读端程序
#include <iostream>
#include <event2/event.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
using namespace std;
void cb(evutil_socket_t fd, short what, void * arg)
{
char buf[256];
int n=read(fd, buf, sizeof(buf));
if (n==-1)
{
cout<<"read is error!\n";
exit(1);
}
cout<<"the buf is "<<buf<<endl;
}
int main()
{
unlink("myfifo");
mkfifo("myfifo", 0664);
int fd=open("myfifo", O_RDONLY | O_NONBLOCK);
struct event_base* base=NULL;
base=event_base_new();
struct event *ev=NULL;
ev=event_new(base, fd, EV_READ | EV_PERSIST, cb, NULL);
event_add(ev, NULL);
event_base_dispatch(base);
event_free(ev);
event_base_free(base);
close(fd);
}
写端程序
#include <iostream>
#include <event2/event.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
using namespace std;
void cb(evutil_socket_t fd, short what, void * arg)
{
char buf[256]="hello world";
static int num=0;
sleep(1);
//printf(buf, "hello world! %d\n", ++num);
cout<<buf<<endl;
write(fd, buf, strlen(buf));
}
int main()
{
int fd=open("myfifo", O_WRONLY | O_NONBLOCK);
struct event_base* base=NULL;
base=event_base_new();
struct event *ev=NULL;
ev=event_new(base, fd, EV_WRITE | EV_PERSIST, cb, NULL);
event_add(ev, NULL);
event_base_dispatch(base);
event_free(ev);
event_base_free(base);
close(fd);
}