C语言 如何在 C 中使用 nanosleep()?什么是“tim.tv_sec”和“tim.tv_nsec”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7684359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 09:51:04  来源:igfitidea点击:

How to use nanosleep() in C? What are `tim.tv_sec` and `tim.tv_nsec`?

cposixsleep

提问by pnizzle

What is the use of tim.tv_secand tim.tv_nsecin the following?

有什么用的tim.tv_sec,并tim.tv_nsec在下面?

How can I sleep execution for 500000microseconds?

如何让执行休眠几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;
}

采纳答案by NPE

Half a second is 500,000,000 nanoseconds, so your code should read:

半秒是 500,000,000 纳秒,所以你的代码应该是:

tim.tv_sec  = 0;
tim.tv_nsec = 500000000L;

As things stand, you code is sleeping for 1.0000005s (1s + 500ns).

就目前情况而言,您的代码休眠了 1.0000005 秒(1 秒 + 500 纳秒)。

回答by Dave

tv_nsecis the sleep time in nanoseconds. 500000us = 500000000ns, so you want:

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

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

回答by glglgl

500000 microseconds are 500000000 nanoseconds. You only wait for 500 ns = 0.5 μs.

500000 微秒是 500000000 纳秒。您只需等待 500 ns = 0.5 μs。

回答by Sunny Shukla

This worked for me ....

这对我有用....

#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 %d\n",ret);
   return 0;
}

回答by E.T

I usually use some #define and constants to make the calculation easy:

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

#define NANO_SECOND_MULTIPLIER  1000000  // 1 millisecond = 1,000,000 Nanoseconds
const long INTERVAL_MS = 500 * NANO_SECOND_MULTIPLIER;

Hence my code would look like this:

因此我的代码看起来像这样:

timespec sleepValue = {0};

sleepValue.tv_nsec = INTERVAL_MS;
nanosleep(&sleepValue, NULL);

回答by Ruslan R. Laishev

More correct variant:

更正确的变体:

{
struct timespec delta = {5 /*secs*/, 135 /*nanosecs*/};
while (nanosleep(&delta, &delta));
}