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>
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.
Example 1: For Linux
C
#include <stdio.h>
#include <unistd.h>
int main()
{
printf("Program to sleep for 10 second in Linux.\n");
sleep(10);
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
#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
#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.
Last Updated :
08 Mar, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...