系统相关
首页 > 系统相关> > LINUX延时函数使用

LINUX延时函数使用

作者:互联网

LINUX 几种常用的延时方式会被信号以及中断打断,如果不对打断进行处理会导致延时时间不精确。

select

void ms_sleep(long lTime)
{
    struct timeval sTime;
    sTime.tv_sec    = lTime/1000;
    sTime.tv_usec   = (lTime%1000)*1000;
    while (select(0, NULL, NULL, NULL, &sTime)<0) 
    {
        if(EINTR != errno)
       {
          perror("my_mSleep nanosleep");
          break;
       }
    }
}

关于select被打断返回剩余时间网上没有太多的介绍,在man里面有这样一句话

(ii) select() may update the timeout argument to indicate how much time was left. pselect() does not change this argument.

nanosleep

void ms_sleep(long lTime)
{
    struct timespec sTime;
    sTime.tv_sec = lTime / 1000;
    sTime.tv_nsec = (lTime % 1000) * 1000000;
    while (nanosleep(&sTime, &sTime)<0)
    {
         if(EINTR != errno)
         {
            perror("my_mSleep nanosleep");
            break;
         }
    }
}

void us_sleep(long lTime)
{
    struct timespec sTime;
    sTime.tv_sec = lTime / 1000;
    sTime.tv_nsec = (lTime % 1000000) * 1000;
    while (nanosleep(&sTime, &sTime)<0)
    {
         if(EINTR != errno)
         {
            perror("my_mSleep nanosleep");
            break;
         }
    }
}

标签:函数,tv,lTime,sTime,延时,LINUX,NULL,select,1000
来源: https://blog.csdn.net/qq_44698084/article/details/116399456