【linux】select实现定时器

/*秒级定时器*/
void seconds_sleep(unsigned     long  seconds)
{
    if(seconds == 0) return;
    struct timeval tv;
    tv.tv_sec=seconds;
    tv.tv_usec=0;
    int err;
    do{
       err=select(0,NULL,NULL,NULL,&tv);
    }while(err<0 && errno==EINTR);
}
 
/*毫秒定时器*/
 
void milliseconds_sleep(unsigned long mSec)
{
    if(mSec == 0) return;
    struct timeval tv;
    tv.tv_sec=mSec/1000;
    tv.tv_usec=(mSec%1000)*1000;
    int err;
    do{
       err=select(0,NULL,NULL,NULL,&tv);
    }while(err<0 && errno==EINTR);
}
 
/*微秒定时器*/
 
void microseconds_sleep(unsigned long uSec)
{
    if(uSec == 0) return;
    struct timeval tv;
    tv.tv_sec=uSec/1000000;
    tv.tv_usec=uSec%1000000;
    int err;
    do{
        err=select(0,NULL,NULL,NULL,&tv);
    }while(err<0 && errno==EINTR);
}
 
 
int main()
{
    int i;
    for(i=0;i<5;++i){
    printf("%d\n",i);
    //seconds_sleep(2);
    //milliseconds_sleep(2000);
    microseconds_sleep(2000000);
    }
}

http://gityuan.com/2019/01/05/linux-poll-select/
https://blog.csdn.net/sjp11/article/details/126312199
https://www.cnblogs.com/sctb/p/17400454.html
https://blog.csdn.net/weixin_37926485/article/details/122810971

你可能感兴趣的:(test,linux,运维,服务器)