/**取得当前毫秒数*/
long now()
{
struct timeval t;
gettimeofday(&t, NULL);
return t.tv_sec * 1000 + t.tv_usec / 1000;
}
/**将一个文件描述符添加到epoll监听, common:是否为客户端连接(相对于监听sock)*/
void add_fd(int fd, boolean common)
{
if(common)
{
int idx;
//查找可用的位置(NULL)
for(idx = 0; idx < MAX_CLIENT && clients[idx] != NULL; idx++);
if(idx == MAX_CLIENT)
{
fprintf(stderr, "max client\n");
close(fd);
return;
}
client_data *client = malloc(sizeof(client_data));
bzero(client, sizeof(client_data));
client->fd = fd;
client->last = now(); //最后一次访问时间
clients[fds[fd] = idx] = client; //做好对应
}
struct epoll_event e;
e.data.fd = fd;
e.events = EPOLLIN | EPOLLET;
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &e);
}