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

ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.