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);
    }
}

————————————————
版权声明:本文为CSDN博主「晓春三月」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/courageously/article/details/107138839

猜你喜欢

转载自blog.csdn.net/modi000/article/details/125263062