C program to demonstrate the nanosleep() function

Here, we are going to demonstrate the nanosleep() function in C programming language.
Submitted by Nidhi, on July 22, 2021

Problem Solution:

In this program, we will use the nanosleep() function. This function is used to halt program execution for a specific time.

Program:

The source code to demonstrate the nanosleep() function is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to demonstrate nanosleep() function

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

enum { SECS = 2,
    NANOSEC = 30 };

int main()
{
    struct timespec r1, r2 = { SECS, NANOSEC };
    int cnt = 0;

    printf("Counter stated..\n");
    while (cnt <= 10) {
        printf("Counter:  %d\n", cnt);
        if (cnt == 5) {
            printf("Sleeping ....\n");
            nanosleep(&r2, &r1);
        }
        cnt++;
    }
    return 0;
}

Output:

Counter stated..
Counter:  0
Counter:  1
Counter:  2
Counter:  3
Counter:  4
Counter:  5
Sleeping ....
Counter:  6
Counter:  7
Counter:  8
Counter:  9
Counter:  10

Explanation:

Here, we used nanosleep() function to sleep program execution for a specific time.

C Advance Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.