Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

posix

sleep

What is the use of tim.tv_sec and tim.tv_nsec in the following?

How can I sleep execution for 500000 microseconds?

#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;
}
like image 594
pnizzle Avatar asked Oct 07 '11 07:10

pnizzle


People also ask

How do you use the Nanosleep function?

If the call is interrupted by a signal handler, nanosleep() returns -1, sets errno to EINTR, and writes the remaining time into the structure pointed to by rem unless rem is NULL. The value of *rem can then be used to call nanosleep() again and complete the specified pause (but see NOTES).

Is Nanosleep a system call?

Linux provides a system call, nanosleep(2) , that in theory can provide nanosecond-level granularity, that is, a sleep of a single nanosecond.


3 Answers

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

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

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

like image 190
NPE Avatar answered Oct 13 '22 22:10

NPE


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

nanosleep((const struct timespec[]){{0, 500000000L}}, NULL);
like image 59
Dave Avatar answered Oct 13 '22 22:10

Dave


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

like image 12
glglgl Avatar answered Oct 14 '22 00:10

glglgl