nanosleep function in C is used to suspend the execution of the program for a specific amount of time for nanoseconds. The function can be is in the <time.h> header in C. Another function to suspend the execution of the program is the sleep function which provides low-level resolution suspension but in nanosleep we have the advantage of pausing the program for nanoseconds i.e., it has high precision.
Syntax:
int nanosleep(const struct timespec *t1, struct timespec *t2)
Both requests and remaining are two addresses of type struct timespec. Both will have two members:
- tv_sec, which is the number of seconds.
- tv_nsec, which is the number of nanoseconds.
Note : The value of tv_nsec should be between 0 to 999999999 or else the program will give an error.
Return value: On successful execution, it returns the value 0 else it returns -1.
Errors occurring while using nanosleep():
The nanosleep() function shall fail if:
- [EINTR] : interrupted by a signal.
- [EINVAL] : The t1 argument specified a nanosecond value less than zero or greater than or equal to 1000 million.
Example:
// C Program to demonstrate
// use of nanosleep
#include <stdio.h>
#include <time.h>
int main()
{
struct timespec remaining, request = { 5, 100 };
printf("Taking a nap...\n");
int response = nanosleep(&request, &remaining);
if (response == 0) {
printf("Nap was Successful .\n");
}
else {
printf("Nap was Interrupted.\n");
}
}
Output
Taking a nap... Nap was Successful .
// C Program to demonstrate
// use of nanosleep
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
struct timespec remaining, request = { 1, 34 };
printf("Running\n");
for (int i = 0; i < 10; ++i) {
printf("loop %d\n", i);
if (i == 4) {
printf("Nap time ...\n");
errno = 0;
if (nanosleep(&request, &remaining) == -1) {
switch (errno) {
case EINTR:
printf("interrupted by a signal "
"handler\n");
break;
case EINVAL:
printf("tv_nsec - not in range or "
"tv_sec is negative\n");
break;
default:
perror("nanosleep");
break;
}
}
}
}
exit(EXIT_SUCCESS);
}
Output
Running loop 0 loop 1 loop 2 loop 3 loop 4 Nap time ... loop 5 loop 6 loop 7 loop 8 loop 9
Example when Errors are generated:
// C Program to demonstrate
// nanosleep errors
#include <errno.h>
#include <stdio.h>
#include <time.h>
int main()
{
struct timespec remaining, request = {
8, -98
}; // giving negative value to generate error in output
printf("Nap started ...\n");
int response = nanosleep(&request, &remaining);
if (response == 0) {
printf("Nap was Successful .\n");
}
else {
printf("Nap Interrupted ...\n");
errno = 0;
if (nanosleep(&request, &remaining) == -1) {
switch (errno) {
case EINTR:
printf("interrupted by a signal handler\n");
break;
case EINVAL:
printf("Value not in range or Value is "
"negative\n");
break;
default:
perror("nanosleep");
break;
}
}
}
}
Output
Nap started ... Nap Interrupted ... Value not in range or Value is negative