C sleep() Function Tutorial

The C programming language provides different functions which sleep() is one of them which is used to stop the current process or thread execution. The sleep() function is used to wait for a specified number of seconds, milliseconds, or minutes.

Include uninstd.h Library In Linux

Different C implementations provides different libraries in order to use the sleep() function. For Linux operating systems the uninstd.h provides sleep() function. So we should import the uninstd.h header like below.

#include <unistd.h>

Include windows.h Library In Windows

Windows operating system C implementations also provides the sleep() function. But the sleep() function is provided with different library than Linux. The Windows.h is used to provide sleep() function. So we should import the Windows.h header with the include like below.

#include <Windows.h>

Sleep 1 Seconds

The sleep function accepts integers and floating point numbers as parameter in order to specify the sleep time interval. In the following example we sleep 1 second.

#include<stdio.h>
 
main()
{
   printf("Sleeping for 1 second.\n");
   sleep(1);
   return 0;
}

Sleep For 10 Seconds

In the following example we sleep for 10 seconds.

#include<stdio.h>
 
main()
{
   printf("Sleeping for 10 seconds.\n");
   sleep(10);
   return 0;
}

Sleep For 100 Milliseconds

As stated previously the sleep() function can be used to sleep for milliseconds. We provide a floating point number like 0.1 to the sleep() function to sleep 100 milliseconds.

#include<stdio.h>
 
main()
{
   printf("Sleep for 100 milisecond to exit.\n");
   sleep(0.10);
   return 0;
}

Sleep For 500 Milliseconds

In the following example we sleep for 500 milliseconds.

#include<stdio.h>
 
main()
{
   printf("Sleep for 500 milisecond to exit.\n");
   sleep(0.50);
   return 0;
}

Sleep with usleep() Function

The C programming language also provides the usleep() function in order to sleep for the specified time as milliseconds. In the following example we sleep for 250 milliseconds.

#include<stdio.h>
 
main()
{
   printf("Sleep for 250 milisecond to exit.\n");
   usleep(250);
   return 0;
}

Leave a Comment