C nanosleep method explanation with example

C nanosleep method explanation with example:

nanosleep method is a unix system method that is used to pause the execution of a program for specific amount of time. In this post, we will learn how to use nanosleep with example.

Another method is sleep that we can use to pause the execution of a C program. In nanosleep, we can also provide the nanoseconds for sleeping time.

In this post, we will learn how to use nanosleep method with examples.

Definition of nanosleep:

nanosleep is defined as below:

int nanosleep(const struct timespec *request, struct timespec *remaining);

It is defined in time.h header file.

Both request 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 tha the value of tv_nsec must be in 0 to 999999999. Otherwise, it will not work.

Return value:

On successfull execution, it returns 0. If it fails for any error or if it is interrupted, it returns -1.

Example program:

Let’s take a look at the below example program:

#include <stdio.h>
#include <time.h>

int main()
{
    struct timespec remaining, request = {3, 500};

    printf("Sleeping ....\n");
    int response = nanosleep(&request, &remaining);

    if (response == 0)
    {
        printf("nanosleep was successfully executed.\n");
    }
    else
    {
        printf("nanosleep execution failed.\n");
    }
}

Here,

  • we have created two timespec objects request and remaining.
  • request is assigned 3 seconds and 500 nanoseconds.
  • The addresses of these objects are passed to nanosleep.
  • We are also checking the return value of nanosleep to determine if it was successfull or failed.

It will print the below output:

Sleeping ....
nanosleep was successfully executed.

You might also like: