Open In App

sleep() Function in C

Last Updated : 18 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

sleep() function in C allows the users to wait for a current thread for a specific time. Other operations of the CPU will function properly but the sleep() function will sleep the present executable for the specified time by the thread.

Header Files Used 

For the Windows platform, we can include windows.h library.

#include<windows.h>

For the Linux platform, we can use unistd.h standard library. We can include this library as shown below 

#include<unistd.h>

Parameter

For Linux systems, the sleep function takes a number of seconds you want the users to wait.

While in Windows systems, it takes the time as the number of milliseconds.

Return Value

The sleep() function in C returns 0 if the requested time has elapsed. Due to signal transmission sleep() returns the unslept quantity, a difference between the requested time to sleep()  and the time it actually slept in seconds.

Examples of sleep() Function in C

Example 1: For Linux 

C
// C program to demonstrate 
// use of sleep function
// till 10 seconds in Linux.
#include <stdio.h>
#include <unistd.h>

int main()
{

      // This line will be executed first
    printf("Program to sleep for 10 second in Linux.\n");

    sleep(10);
    // after 10 seconds this next line will be executed.
  
    printf("This line will be executed after 10 second.");

    return 0;
}

Output
Program to sleep for 10 second in Linux.
This line will be executed after 10 second.

Example 2: For Windows

C
// C program to demonstrate
// use of sleep function
// till 10 milliseconds in Windows.
#include <stdio.h>
#include <Windows.h>

int main()
{

    printf("Program to sleep for 10 second in Windows.\n");

    Sleep(10);

    printf("This line will be executed after 10 millisecond.");

    return 0;
}

Output

Program to sleep for 10 milliseconds in Windows.
This line will be executed after 10 milliseconds.

Example 3:

C
// C program to demonstrate 
// use of sleep function
// till 10 milliseconds 
#include <stdio.h>
#include <unistd.h>

int main()
{

    printf("Program will sleep for 10 millisecond .\n");

    sleep(0.01);

    printf("This line will be executed after 10 millisecond.");

    return 0;
}

Output
Program will sleep for 10 millisecond .
This line will be executed after 10 millisecond.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads