posix - POSIX - 在C中,如何使用nanosleep() 什么是`tim.tv_sec`和`tim.tv_nsec`?

以下是tim.tv_sectim.tv_nsec的用法?

如何执行500000微秒的睡眠?


#include <stdio.h>


#include <time.h>



int main()


{


 struct timespec tim, tim2;


 tim.tv_sec = 1;


 tim.tv_nsec = 500;



 if(nanosleep(&tim , &tim2) < 0 ) 


 {


 printf("Nano sleep system call failed n");


 return -1;


 }



 printf("Nano sleep successfull n");



 return 0;


}



时间:

半秒是50万纳秒,所以,你的代码应该是:


tim.tv_sec = 0;


tim.tv_nsec = 500000000L;



事实上,你的代码是休眠1.000 0005s(1s 500ns )。

tv_nsec是以纳秒为单位的睡眠时间,500000us =500000000ns,所以你想:


nanosleep((const struct timespec[]){{0, 500000000L}}, NULL);



我通常使用一些#define和常量来简化计算:


#define NANO_SECOND_MULTIPLIER 1000000 // 1 millisecond = 1,000,000 Nanoseconds


const long INTERVAL_MS = 500 * NANO_SECOND_MULTIPLIER;



因此,我的代码将如下所示:


timespec sleepValue = {0};



sleepValue.tv_nsec = INTERVAL_MS;


nanosleep(&sleepValue, NULL);



这对我起了作用。


#include <stdio.h>


#include <time.h> /* Needed for struct timespec */



int nsleep(long miliseconds)


{


 struct timespec req, rem;



 if(miliseconds > 999)


 { 


 req.tv_sec = (int)(miliseconds / 1000); /* Must be Non-Negative */


 req.tv_nsec = (miliseconds - ((long)req.tv_sec * 1000)) * 1000000; /* Must be in range of 0 to 999999999 */


 } 


 else


 { 


 req.tv_sec = 0; /* Must be Non-Negative */


 req.tv_nsec = miliseconds * 1000000; /* Must be in range of 0 to 999999999 */


 } 



 return nanosleep(&req , &rem);


}



int main()


{


 int ret = nsleep(2500);


 printf("sleep result %dn",ret);


 return 0;


}



更正确的变体:


{


struct timespec delta = {5 /*secs*/, 135 /*nanosecs*/};


while (nanosleep(&delta, &delta));


}



...