epoll in事件触发时机
第一种情况,当设置了in,并且客户端发送数据到达会触发in事件
第二种情况,设置in,但是客户端发送数据100字节,服务器读取20字节,不再触发in直到再次设置in或有新数据到达。
第三种情况,设置in,如果client关闭(close socket或程序关闭),会触发in事件,recv返回0,如果没有del掉event,并且设置out事件,会触发out事件,如果一直在设置(询问)in事件,则会一直收到in事件。对于拔掉网线与断电情况,recv返回-1,erron为ETIMEOUT,如果没有设置keep-alive不会触发in事件,如果设置了keep-alive会触发一次in事件,但是在接收in事件后设置out事件后不会触发out事件。
第三种情况,没有设置keep-alive,客户端close socket或程序关闭:
#include <iostream>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <netinet/tcp.h>
using namespace std;
#define MAXLINE 5
#define OPEN_MAX 100
#define LISTENQ 20
#define SERV_PORT 6002
#define INFTIM 1000
int socket_set_keepalive( int fd)
{
int ret, error, flag, alive, idle, cnt, intv;
/* Set: use keepalive on fd */
alive = 1;
if (setsockopt (fd, SOL_SOCKET, SO_KEEPALIVE, &alive, sizeof alive) != 0)
{
printf ("Set keepalive error: %s.\n" , strerror (errno));
return -1;
}
/* 10秒钟无数据,触发保活机制,发送保活包 */
idle = 10;
if (setsockopt(fd, SOL_TCP, TCP_KEEPIDLE , &idle, sizeof idle) != 0)
{
printf ("Set keepalive idle error: %s.\n" , strerror (errno));
return -1;
}
/* 如果没有收到回应,则5秒钟后重发保活包 */
intv = 5;
if (setsockopt(fd, SOL_TCP, TCP_KEEPINTVL , &intv, sizeof intv) != 0)
{
printf ("Set keepalive intv error: %s.\n", strerror (errno));
return -1;
}
/* 连续3次没收到保活包,视为连接失效 */
cnt = 3;
if (setsockopt(fd, SOL_TCP, TCP_KEEPCNT , &cnt, sizeof cnt) != 0)
{
printf ("Set keepalive cnt error: %s.\n", strerror (errno));
return -1;
}
return 0;
}
void setnonblocking(int sock)
{
int opts;
opts=fcntl(sock,F_GETFL);
if(opts<0)
{
perror("fcntl(sock,GETFL)");
exit(1);
}
opts = opts|O_NONBLOCK;
if(fcntl(sock,F_SETFL,opts)<0)
{
perror("fcntl(sock,SETFL,opts)");
exit(1);
}
}
int main()
{
int i, maxi, listenfd, connfd, sockfd,epfd,nfds;
ssize_t n;
char line[MAXLINE];
socklen_t clilen;
//声明epoll_event结构体的变量,ev用于注册事件,数组用于回传要处理的事件