Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sleep function in C11

Tags:

c

sleep

c11

I want to sleep in a C11 program. Neither usleep (in unistd.h) nor nanosleep (in time.h) are declared with the -std=c11 option of both gcc (4.8.2) and clang (3.2).

A grep sleep /usr/include/*.h doesn't reveal any other likely sleep candidates.

I need a sleep with at least millisecond precision.

How do I sleep in C11?

like image 231
cdjc Avatar asked Apr 07 '14 22:04

cdjc


People also ask

What is the use of sleep () in C?

The function sleep gives a simple way to make the program wait for a short interval. If your program doesn't use signals (except to terminate), then you can expect sleep to wait reliably throughout the specified interval.

How do you use sleep command in C++?

h> , and use this function for pausing your program execution for desired number of seconds: sleep(x); x can take any value in seconds.

What does sleep mean in coding?

The sleep() function suspends (waits) execution of the current thread for a given number of seconds. Python has a module named time which provides several useful functions to handle time-related tasks. One of the popular functions among them is sleep() .

In which library is sleep function?

sleep() function is provided by unistd. h library which is a short cut of Unix standard library.


1 Answers

Use -std=gnu11 instead of -std=c11 (this works for both clang and gcc). This will cause the <time.h> header to define nanosleep.

Another alternative to nanosleep, calling pselect on a null file descriptor with a timeout, also only works with -std=gnu11 and not -std=c11

For an example of both:

#include <stdio.h>
#include <sys/select.h>

int main()  // Compile with -std=gnu11 (and not -std=c11)
{
   struct timespec ts1 = {
       .tv_sec = 0,
       .tv_nsec = 500*1000*1000
   };
   printf("first\n");
   nanosleep(&ts1, NULL);
   printf("second\n");
   pselect(0, NULL, NULL, NULL, &ts1, NULL);
   printf("third\n");
}
like image 198
cdjc Avatar answered Sep 29 '22 02:09

cdjc