libevent库简单使用

 

 

创建一个事件处理框架并显示系统中可以用那些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);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值