Linux IO复用之epoll

epoll

#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/epoll.h>

int main()
{
	int epfd = epoll_create(256);
	int sockSrv = socket(AF_INET, SOCK_STREAM, 0);
	
	struct epoll_event ev;
	ev.data.fd = sockSrv;
	ev.events = EPOLLIN|EPOLLET;
	epoll_ctl(epfd,  EPOLL_CTL_ADD, sockSrv, &ev);

	struct sockaddr_in addrSrv;
	bzero(&addrSrv, sizeof(addrSrv));
	addrSrv.sin_family = AF_INET;
	addrSrv.sin_addr.s_addr = htonl(INADDR_ANY);
	addrSrv.sin_port = htons(6000);
	bind(sockSrv, (struct sockaddr*)&addrSrv, sizeof(addrSrv));
	
	listen(sockSrv, 3);
	
	int sockConn;
	struct sockaddr_in addrConn;
	int len = sizeof(addrConn);

	int nfds;
	struct epoll_event events[20];

	char buf[100] = {0};
	while(1)
	{
		nfds = epoll_wait(epfd, events, 20, 500);

		int i;
		for(i=0; i<nfds; i++)
		{
			if(events[i].data.fd == sockSrv)
			{
				sockConn = accept(sockSrv, (struct sockaddr*)&addrConn, &len);

				printf("new connect.\n");

				ev.data.fd = sockConn;
				ev.events = EPOLLIN|EPOLLET;
				epoll_ctl(epfd, EPOLL_CTL_ADD, sockConn, &ev);
			}
			else if(events[i].events & EPOLLIN)
			{
				int tmpSock = events[i].data.fd;
				if(tmpSock < 0)
					continue;

				int n = read(sockConn, buf, 100);
				if(0 == n)
				{
					close(sockConn);
					events[i].data.fd = -1;
				}
				else
					printf("server recv:%s\n", buf);

				ev.data.fd = tmpSock;
				ev.events = EPOLLOUT|EPOLLET;
				epoll_ctl(epfd, EPOLL_CTL_MOD, tmpSock, &ev);
			}
			else if(events[i].events & EPOLLOUT)
			{
				int tmpSock = events[i].data.fd;

				write(tmpSock, "parent", strlen("parent"));

				ev.data.fd = tmpSock;
				ev.events = EPOLLIN|EPOLLET;
				epoll_ctl(epfd, EPOLL_CTL_MOD, tmpSock, &ev);
			}
		}
	}
	
	close(sockSrv);
	
	return -1;
}


你可能感兴趣的:(Linux IO复用之epoll)