Linux学习之epoll代码初学

#include
#include
#include
#include
#include

#include
#include
#include
#include 

#define BUFFER_LENGTH 128
#define EVENTS_LENGTH 128
int main(){

	int listenfd = socket(AF_INET,SOCK_STREAM,0);
	if(listenfd == -1) return -1;

	struct sock_addr_server ser_addr;
	ser_addr.sin_family = AF_INET;
	ser_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	ser_addr.sin_port = htons(9999);

	if (-1 == bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr))) {
			return -2;
	}
	listen(listenfd,10);
	// 10代表同时连接的队列的最大长度

	// 设置非阻塞
	int flag = fcntl(listenfd,F_GETFL,0);
	flag | = O_NONBLOCK;
	fcntl(listenfd,F_SETFL,flag);
	
	
	int connfd = accept(listenfd,(struct sockaddr*)&ser_addr,&len);
	//int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);

	//  创建epoll对象
	int epfd = epoll_create;
	struct epoll_event ev,events[EVENTS_LENGTH];

	//  以读事件添加。
	ev.events = EPOLLIN;
	ev.data.fd = listenfd;
	epoll_ctl(epfd,EPOLL_CTL_ADD,listenfd,&ev);

	//  开始轮询
	while(1){
		int nready = epoll_wait(epfd,events,EVENTS_LENGTH,-1);
		//	这里超时时间设置为-1是阻塞 0是立即返回
		printf("------- %d\n", nready);
		int i = 1;
		for (int i = 0; i < nready; i++){
			int clientfd = events[i].data.fd;

			// 先处理 listen
			if(listenfd == clientfd){
				struct sockaddr_in client;
				socklen_t len = sizeof(client);
				int connfd = accept(client,(struct sockaddr_in)&client,&len);
				if(conn == -1) return -1;

				printf("accept: %d\n", connfd);
				
				// 设置为边缘触发	并将连接添加到epoll中管理
				epoll.events = EPOLLIN |EPOLLET;
				ev.data.fd = connfd;
				epoll_ctl(epfd, EPOLL_CTL_ADD, connfd, &ev);
			}
		}
	}
	
	
}

你可能感兴趣的:(Linux,reactor,linux,学习,运维)