C 中的 sleep() 函數允許用戶等待當前線程特定的時間。 CPU 的其他操作將正常運行,但 sleep() 函數將在線程指定的時間內休眠當前的可執行文件。
使用的頭文件
對於Windows平台,我們可以包含windows.h庫。
#include<windows.h>
對於Linux平台,我們可以使用unistd.h標準庫。我們可以包含這個庫,如下所示
#include<unistd.h>
參數
為了Linux係統,sleep函數需要幾秒的時間你希望用戶等待。
而在Windows係統中,時間以毫秒為單位。
返回值
如果請求的時間已過,C 中的 sleep() 函數將返回 0。由於信號傳輸,sleep() 返回未睡眠數量,即 sleep() 請求的時間與實際睡眠時間(以秒為單位)之間的差異。
C 語言sleep() 函數示例
示例 1:對於Linux
// 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;
}
輸出
Program to sleep for 10 second in Linux. This line will be executed after 10 second.
示例 2:對於 Windows
// 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;
}
輸出
Program to sleep for 10 milliseconds in Windows.
This line will be executed after 10 milliseconds.
示例 3:
// 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;
}
輸出
Program will sleep for 10 millisecond . This line will be executed after 10 millisecond.
相關用法
- C語言 strchr()用法及代碼示例
- C語言 strcpy()用法及代碼示例
- C語言 strcat()用法及代碼示例
- C語言 setlocale()用法及代碼示例
- C語言 sin()用法及代碼示例
- C語言 sinh()用法及代碼示例
- C語言 sqrt()用法及代碼示例
- C語言 signal()用法及代碼示例
- C語言 setbuf()用法及代碼示例
- C語言 setvbuf()用法及代碼示例
- C語言 scanf()用法及代碼示例
- C語言 sscanf()用法及代碼示例
- C語言 strtod()用法及代碼示例
- C語言 strtol()用法及代碼示例
- C語言 strtoul()用法及代碼示例
- C語言 system()用法及代碼示例
- C語言 srand()用法及代碼示例
- C語言 strncat()用法及代碼示例
- C語言 strcmp()用法及代碼示例
- C語言 strncmp()用法及代碼示例
- C語言 strcoll()用法及代碼示例
- C語言 strncpy()用法及代碼示例
- C語言 strerror()用法及代碼示例
- C語言 strrchr()用法及代碼示例
- C語言 strstr()用法及代碼示例
注:本文由純淨天空篩選整理自kamleshjoshi18大神的英文原創作品 sleep() Function in C。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。