定时器的设计

  如果某一用户connect()到服务器之后,长时间不交换数据,一直占用服务器端的文件描述符,导致连接资源的浪费。这时候就应该利用定时器把这些超时的非活动连接释放掉,关闭其占用的文件描述符。这种情况也很常见,当你登录一个网站后长时间没有操作该网站的网页,再次访问的时候你会发现需要重新登录。

  网络程序需要处理的第三类是定时事件,比如定期检测一个客户连接的活动状态。

  主要有三种
  1.socket选项中的SO_RCVTIMEO和SO_SNDTIMEO。
  2.SIGANLRM信号
  3.I/O复用调用的超时参数

1 socket 选项 SO_RCVTIMEO和SO_SNDTIMEO

SO_RCVTIMEO和SO_SNDTIMEO,他们分别是用来设置socket接收数据超时时间和发送数据超时时间。,这个选项仅适用于socket专用系统调用。

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>


//超时连接函数
int timeout_connect( const char* ip, int port, int time )
{
    int ret = 0;
    struct sockaddr_in address;
	//一定要记得初始化,因为很多时候同一片内存区域,会多次使用到
    bzero( &address, sizeof( address ) );
    address.sin_family = AF_INET;
    inet_pton( AF_INET, ip, &address.sin_addr );
    address.sin_port = htons( port );

    int sockfd = socket( PF_INET, SOCK_STREAM, 0 );
    assert( sockfd >= 0 );

    struct timeval timeout;
	//一个结构体,一个是秒,一个是微妙
    timeout.tv_sec = time;
    timeout.tv_usec = 0;
    socklen_t len = sizeof( timeout );
	
	//端口复用相关的
    ret = setsockopt( sockfd, SOL_SOCKET, SO_SNDTIMEO, &timeout, len );
    assert( ret != -1 );

    ret = connect( sockfd, ( struct sockaddr* )&address, sizeof( address ) );
    if ( ret == -1 )
    {
        if( errno == EINPROGRESS )
        {
            printf( "connecting timeout\n" );
            return -1;
        }
        printf( "error occur when connecting to server\n" );
        return -1;
    }

    return sockfd;
}

int main( int argc, char* argv[] )
{
    if( argc <= 2 )
    {
        printf( "usage: %s ip_address port_number\n", basename( argv[0] ) );
        return 1;
    }
    const char* ip = argv[1];
    int port = atoi( argv[2] );

    int sockfd = timeout_connect( ip, port, 10 );
    if ( sockfd < 0 )
    {
        return 1;
    }
    return 0;
}

2、SIGALRM 信号

  一般来说,SIGALRM信号按照固定的频率生成,即由alarm或setitimer函数设置的定时周期T保持不变。如果某个定时任务的超时事件不是T的整数倍,那么它实际被执行的事件和预期的事件略有偏差,因此定时周期T反映了定时的精度。
  本节主要通过一个实例———处理非活动连接,来介绍如何使用SIGALRM信号定时。

2.1 基于升序链表的定时器

  定时器至少包括两个成员,一个是超时时间(相对时间或者绝对时间)和一个任务回调函数。有的时候(回调函数的参数,是否定时重启)。如果使用链表作为容器来串联所以的定时器,则每个定时器还有包含一个指向下一个定时器的指针成员,假如是双向的,则是两个。

#ifndef LST_TIMER
#define LST_TIMER

#include <time.h>

#define BUFFER_SIZE 64
class util_timer;

//定义  用户数据结构, 客户端socket地址、socket文件描述符、读缓存和定时器

struct client_data
{
    sockaddr_in address;
    int sockfd;
    char buf[ BUFFER_SIZE ];
    util_timer* timer;
};


//定时器 类
class util_timer
{
public:
    util_timer() : prev( NULL ), next( NULL ){}

public:
	//任务的超时时间   使用的是绝对时间
   time_t expire; 
   //任务回调函数,想想pthread回调
   void (*cb_func)( client_data* );
   
   //回调函数处理的客户数据,由定时器的执行者传递回给回调函数
   client_data* user_data;
   
   //前后两个指针
   util_timer* prev;
   util_timer* next;
};


//定时器链表。是一个升序、双向链表、且带有头节点和尾接点
class sort_timer_lst
{
public:
    sort_timer_lst() : head( NULL ), tail( NULL ) {}
	
	//链表销毁时,删除其中所以的定时器
    ~sort_timer_lst()
    {
        util_timer* tmp = head;
        while( tmp )
        {
            head = tmp->next;
            delete tmp;
            tmp = head;
        }
    }
	
	/* 将目标定时器  timer 添加到链表中*/
	
    void add_timer( util_timer* timer )
    {
        if( !timer )
        {
            return;
        }
        if( !head )
        {
            head = tail = timer;
            return; 
        }
		// 如果目标定时器的超时时间小于所有定时器的超时时间,则把该定时器插入链表头部
		// 作为链表的头节点,否则就需要调用重载函数 add_timer( timer, head );
		// 将其插入到合适的位置,以保持链表的有序性
        if( timer->expire < head->expire )
        {
            timer->next = head;
            head->prev = timer;
            head = timer;
            return;
        }
        add_timer( timer, head );
    }
	
	//当某个定时任务发生变化时,调正对应的定时器在链表中的位置,这个函数
	//只考虑被调整的定时器的超时时间延长的情况,即该定时器需要往链表的尾部移动
    void adjust_timer( util_timer* timer )
    {
        if( !timer )
        {
            return;
        }
        util_timer* tmp = timer->next;
        if( !tmp || ( timer->expire < tmp->expire ) )
        {
            return;
        }
        if( timer == head )
        {
            head = head->next;
            head->prev = NULL;
            timer->next = NULL;
            add_timer( timer, head );
        }
        else
        {
            timer->prev->next = timer->next;
            timer->next->prev = timer->prev;
            add_timer( timer, timer->next );
        }
    }
	
	//将目标定时器从 timer 从链表中删除
    void del_timer( util_timer* timer )
    {
        if( !timer )
        {
            return;
        }
		//这里表示 链表中只有一个定时器
        if( ( timer == head ) && ( timer == tail ) )
        {
            delete timer;
            head = NULL;
            tail = NULL;
            return;
        }
		
		//这些链表的操作,最好还是去画一下。
		//至少是两个定时器,且目标定时器是链表的头节点,
        if( timer == head )
        {
            head = head->next;
            head->prev = NULL;
            delete timer;
            return;
        }
		
		//至少是两个定时器,且目标定时器是链表的尾节点,
        if( timer == tail )
        {
            tail = tail->prev;
            tail->next = NULL;
            delete timer;
            return;
        }
		
		//如果目标定时器在中间,则把它前后的定时器串联起来,
		//然后删除目标定时器
        timer->prev->next = timer->next;
        timer->next->prev = timer->prev;
        delete timer;
    }
	
	
	
	//SIGALRM 信号每次触发,就执行依次tick函数
    void tick()
    {
        if( !head )
        {
            return;
        }
        printf( "timer tick\n" );
        time_t cur = time( NULL );
        util_timer* tmp = head;
		//从头节点开始处理每个定时器,直到遇到一个尚未到期的定时器,
		//这个是关键所在
		
        while( tmp )
        {
			//因为在这里的每个计时器,都是选用绝对时间作为超时值
			//可以直接用定时器的超时值与当前系统时间进行比较来判断是否超时
            if( cur < tmp->expire )
            {
                break;
            }
			
			//调用回调函数,执行定时任务
            tmp->cb_func( tmp->user_data );
			//执行完回调任务就i将这个节点删除,并且重置头节点
			
            head = tmp->next;
            if( head )
            {
                head->prev = NULL;
            }
            delete tmp;
            tmp = head;
        }
    }

private:
	//一个重载的辅助函数,它被公有的add_timer函数与adjust_timer 函数调用
	//该函数表示将目标定时器上timer添加 到节点lst_head之后的分链表中
	
	
    void add_timer( util_timer* timer, util_timer* lst_head )
    {
        util_timer* prev = lst_head;
        util_timer* tmp = prev->next;
		//遍历lst_head节点之后的部分链表,直到找到一个超时时间大于目标定时器的超时
		//时间的节点,并将目标定时器插入到该节点之前。
        while( tmp )
        {
            if( timer->expire < tmp->expire )
            {
                prev->next = timer;
                timer->next = tmp;
                tmp->prev = timer;
                timer->prev = prev;
                break;
            }
            prev = tmp;
            tmp = tmp->next;
        }
		
		//如果遍历完lst_head 节点之后的部分链表,仍未找到超时时间大于目标时间的
		//则将目标定时器插入链表尾部,并把它设置为链表新的尾节点。
        if( !tmp )
        {
            prev->next = timer;
            timer->prev = prev;
            timer->next = NULL;
            tail = timer;
        }
        
    }

private:
    util_timer* head;
    util_timer* tail;
};

#endif

  为了方便阅读,可以将其放在头文件里sort_timer_lst是一个升序链表。其核心函数tick相当于一个心搏函数,它每隔一段时间就执行一次,以检测并处理到期的任务。判断定时任务到期的依据是定时器的expire值小于当前的系统时间。从执行效率来看,添加定时器的时间复杂度是O(n),删除定时器的复杂度是O(1),执行定时任务的时间复杂度是O(1)。

2.2 处理非活动连接

  非活跃,是指客户端(这里是浏览器)与服务器端建立连接后,长时间不交换数据,一直占用服务器端的文件描述符,导致连接资源的浪费。

  处理非活动连接—就是升序定时器链表的实际应用。服务器程序通常要定时处理非活动连接:给客户端发一个重连请求,或者关闭该连接,或者其他。Linux在内核中提供了对连接是否处于活动状态的定期检查机制,我们可以通过socket选项KEPPALIVE来激活它,不过使用这种方式将应用程序对连接的管理变得复杂。因此我们可以考虑在应用层实现类似于KEEPALIVE的机制,以管理长时间处理非活动状态的连接,比如利用alarm函数周期性地触发SIGALRM信号,该信号的信号处理函数利用管道通知主循环执行定时器链表上的定时任务=====关闭非活动的连接。

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <assert.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/epoll.h>
#include <pthread.h>
#include "lst_timer.h"

#define FD_LIMIT 65535
#define MAX_EVENT_NUMBER 1024
#define TIMESLOT 5

static int pipefd[2];

//利用升序链表来管理定时器

static sort_timer_lst timer_lst;
static int epollfd = 0;

//给文件描述符设置成非阻塞
int setnonblocking( int fd )
{
    int old_option = fcntl( fd, F_GETFL );
    int new_option = old_option | O_NONBLOCK;
    fcntl( fd, F_SETFL, new_option );
    return old_option;
}

//在epool树上添加新的节点
void addfd( int epollfd, int fd )
{
    epoll_event event;
    event.data.fd = fd;
    event.events = EPOLLIN | EPOLLET;
    epoll_ctl( epollfd, EPOLL_CTL_ADD, fd, &event );
    setnonblocking( fd );
}


void sig_handler( int sig )
{
    int save_errno = errno;
    int msg = sig;
    send( pipefd[1], ( char* )&msg, 1, 0 );
    errno = save_errno;
}

void addsig( int sig )
{
    struct sigaction sa;
    memset( &sa, '\0', sizeof( sa ) );
    sa.sa_handler = sig_handler;
    sa.sa_flags |= SA_RESTART;
    sigfillset( &sa.sa_mask );
    assert( sigaction( sig, &sa, NULL ) != -1 );
}


// 定时处理任务,实际上就是调用tick函数
void timer_handler()
{
    timer_lst.tick();
	//因为以恶alarm调用只会引起一次SIGALRN信号,所以需要重新定时
    alarm( TIMESLOT );
}


//定时器回调函数,删除非活动非活动连接 socket上的注册时间,并关闭
void cb_func( client_data* user_data )
{
    epoll_ctl( epollfd, EPOLL_CTL_DEL, user_data->sockfd, 0 );
    assert( user_data );
    close( user_data->sockfd );
    printf( "close fd %d\n", user_data->sockfd );
}

int main( int argc, char* argv[] )
{
    if( argc <= 2 )
    {
        printf( "usage: %s ip_address port_number\n", basename( argv[0] ) );
        return 1;
    }
    const char* ip = argv[1];
    int port = atoi( argv[2] );

    int ret = 0;
    struct sockaddr_in address;
    bzero( &address, sizeof( address ) );
    address.sin_family = AF_INET;
    inet_pton( AF_INET, ip, &address.sin_addr );
    address.sin_port = htons( port );

    int listenfd = socket( PF_INET, SOCK_STREAM, 0 );
    assert( listenfd >= 0 );

    ret = bind( listenfd, ( struct sockaddr* )&address, sizeof( address ) );
    assert( ret != -1 );

    ret = listen( listenfd, 5 );
    assert( ret != -1 );

    epoll_event events[ MAX_EVENT_NUMBER ];
    int epollfd = epoll_create( 5 );
    assert( epollfd != -1 );
    addfd( epollfd, listenfd );

    ret = socketpair( PF_UNIX, SOCK_STREAM, 0, pipefd );
    assert( ret != -1 );
    setnonblocking( pipefd[1] );
    addfd( epollfd, pipefd[0] );

    // add all the interesting signals here
    addsig( SIGALRM );
    addsig( SIGTERM );
    bool stop_server = false;

    client_data* users = new client_data[FD_LIMIT]; 
    bool timeout = false;
    alarm( TIMESLOT );//定时

    while( !stop_server )
    {
        int number = epoll_wait( epollfd, events, MAX_EVENT_NUMBER, -1 );
        if ( ( number < 0 ) && ( errno != EINTR ) )
        {
            printf( "epoll failure\n" );
            break;
        }
    
        for ( int i = 0; i < number; i++ )
        {
            int sockfd = events[i].data.fd;
			//处理新的客户连接
            if( sockfd == listenfd )
            {
                struct sockaddr_in client_address;
                socklen_t client_addrlength = sizeof( client_address );
                int connfd = accept( listenfd, ( struct sockaddr* )&client_address, &client_addrlength );
                addfd( epollfd, connfd );
                users[connfd].address = client_address;
                users[connfd].sockfd = connfd;
				//创建定时器,设置其回调函数与超时时间,然后绑定
				//定时器与用户数据,最后将定时器添加到链表
				
                util_timer* timer = new util_timer;
                timer->user_data = &users[connfd];
                timer->cb_func = cb_func;
                time_t cur = time( NULL );
                timer->expire = cur + 3 * TIMESLOT;
                users[connfd].timer = timer;
                timer_lst.add_timer( timer );
            }
            else if( ( sockfd == pipefd[0] ) && ( events[i].events & EPOLLIN ) )
            {
                int sig;
                char signals[1024];
                ret = recv( pipefd[0], signals, sizeof( signals ), 0 );
                if( ret == -1 )
                {
                    // handle the error
                    continue;
                }
                else if( ret == 0 )
                {
                    continue;
                }
                else
                {
                    for( int i = 0; i < ret; ++i )
                    {
                        switch( signals[i] )
                        {
                            case SIGALRM:
                            {
								//用timeout 变量来标记有定时任务需要处理,但不立即处理,
								//这是因为定时任务的优先级不是很高,我们优先处理其他更重要的事
                                timeout = true;
                                break;
                            }
                            case SIGTERM:
                            {
                                stop_server = true;
                            }
                        }
                    }
                }
            }
            else if(  events[i].events & EPOLLIN )
            {
				//处理客户端发送过来的数据
                memset( users[sockfd].buf, '\0', BUFFER_SIZE );
                ret = recv( sockfd, users[sockfd].buf, BUFFER_SIZE-1, 0 );
                printf( "get %d bytes of client data %s from %d\n", ret, users[sockfd].buf, sockfd );
                util_timer* timer = users[sockfd].timer;
                if( ret < 0 )
                {
					//如果发生读错误,则关闭连接,移除响应的定时器
                    if( errno != EAGAIN )
                    {
                        cb_func( &users[sockfd] );
                        if( timer )
                        {
                            timer_lst.del_timer( timer );
                        }
                    }
                }
                else if( ret == 0 )
                {
					//如果对方已经关闭连接,我们也关闭连接,并移除对应的定时器
                    cb_func( &users[sockfd] );
                    if( timer )
                    {
                        timer_lst.del_timer( timer );
                    }
                }
                else
                {	
					//假如读数据没有问题,则重新调正对应的定时器即可。
                    //send( sockfd, users[sockfd].buf, BUFFER_SIZE-1, 0 );
                    if( timer )
                    {
                        time_t cur = time( NULL );
                        timer->expire = cur + 3 * TIMESLOT;
                        printf( "adjust timer once\n" );
                        timer_lst.adjust_timer( timer );
                    }
                }
            }
            else
            {
                // others
            }
        }

        if( timeout )
        {
			//最后处理定时事件
            timer_handler();
            timeout = false;
        }
    }

    close( listenfd );
    close( pipefd[1] );
    close( pipefd[0] );
    delete [] users;
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值