nanosleep() -- 更精確的延遲 -----一個使用用例


[常規] nanosleep() -- 更精確的延遲 

[復制鏈接]
   

4220

主題

5152

帖子

3萬

積分

GROAD

曲徑通幽,安覓芳蹤。

Rank: 6Rank: 6

積分
30607
跳轉到指定樓層
樓主
 
  發表於 2010-8-22 00:08:53 只看該作者 回帖獎勵
原型:
#include <time.h>
int  nanosleep( const  struct  timespec  * req ,  struct  timespec  * rem);

說明:
此函數將調用進程掛起,直到 req 里所指的時間結束。req 是 struct timespec 結構體的指針。struct timespec 結構體定義如下:
struct  timespec  {
    time_t  tv_sec;         /* 秒 */
    long    tv_nsec;        /* 納秒 */
};
如果在調用 nanosleep() 睡眠期間被信號所中斷,nanosleep() 就會返回 -1,同時設置 errno 為 EINTR,並且會將剩余的時間寫入由 rem 所指向同樣時 struct timespec 類型的結構體中,如果 rem 為 NULL,就不會記錄剩余時間。當信號處理完畢時,還會繼續調用 nanosleep() 直到剩余時間用完為止。

測試程序:
#include <stdio.h>
#include <time.h>
#include <signal.h>
#include <errno.h>

void  sigfunc ( int  sig_no)
{
      int  temp  =  1000;
      while ( temp --  >  0)
     ;
}



int  msleep ( unsigned  long  milisec ,  int  temp)
{
      struct  timespec  req  =  { 0 },  rem  =  { 0 };
      time_t  sec  = ( int)( milisec  /  1000);
      milisec  =  milisec  - ( sec  *  1000);
      req . tv_sec  =  sec;             /*秒*/
      req . tv_nsec  =  milisec  *  1000000L;     /*納秒*/
      while ( nanosleep ( & req ,  & req==  - 1  &&  errno  ==  EINTR{
          printf ( "測試-%d被信號中斷,剩余時間為: %ld秒%ld納秒 \n " ,  temp ,  req . tv_sec ,  req . tv_nsec);
          continue;
      }
      return ( 1);
}


int  main()
{
      struct  sigaction  sa  =  { 0 };
      sa . sa_handler  =  & sigfunc;
      sigaction ( SIGINT ,  & sa ,  NULL);    //安裝信號處理函數

      unsigned  long  a  =  0;
      int  temp  =  1;
      scanf ( "%ld" ,  & a);

      for (;;)  {
          if ( a  ==  5{
              printf ( "testing-%d \n " ,  temp);
              msleep ( a * 1000 ,  temp);   //將 nanosleep() 封裝在 msleep() 中
             temp++;
        }
  else
              usleep ( 1000000);
      }
      return ( 1);
}
運行與輸出:
$ ./nanosleep 
5
testing-1
testing-2
^C測試-2被信號中斷,剩余時間為: 4秒120263116納秒
^C測試-2被信號中斷,剩余時間為: 3秒440359866納秒
^C測試-2被信號中斷,剩余時間為: 2秒320431341納秒
^C測試-2被信號中斷,剩余時間為: 1秒320495448納秒
testing-3
... ...
上面,^C 表示按下 Ctrl + c 組合鍵,發出中斷函數信號。
 
 from:http://www.groad.net/bbs/thread-2621-1-1.html
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM