需要接收端和测试端的可以看这篇
个人单纯测试方法
主要修改epoll_wait(epfd, ev_ret, EVENTS, -1)第 四个参数,对应java层 nativePollOnce(ptr, nextPollTimeoutMillis)的第二个参数;为啥要测试,就是为了理解这个方法到底是怎么执行的
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/epoll.h>
#include <arpa/inet.h>
#define EVENTS 12
int main(){
int sock1;
sockaddr_in addr1;
int epfd;
epoll_event ev, ev_ret[EVENTS];
char buf[2048];
int i;
int nfds;
int n;
sock1 = socket(AF_INET, SOCK_DGRAM, 0);
addr1.sin_family = AF_INET;
inet_pton(AF_INET, "127.0.0.1", &addr1.sin_addr.s_addr);
addr1.sin_port = htons(11111);
bind(sock1, (sockaddr*)&addr1, sizeof(addr1));
//参数不小于0就行
epfd = epoll_create(1);
if(epfd < 0){
perror("epoll_create");
return 1;
}
memset(&ev, 0, sizeof(ev));
ev.events = EPOLLIN;//只读
ev.data.fd = sock1;//把sock1加到epoll
if(epoll_ctl(epfd, EPOLL_CTL_ADD, sock1, &ev) != 0){
perror("epoll_ctl");
return 1;
}
while(1){
printf("before epoll_wait\n");
//在这里会阻塞,只等待10秒,超过10秒,epoll_wait函数结束,返回0给nfds.
nfds = epoll_wait(epfd, ev_ret, EVENTS, -1);
if(nfds < 0){
perror("epoll_wait nfds");
return 1;
}
printf("after epoll_wait\n");
}
close(sock1);
return 0;
}
网友评论