在 Ubuntu(Linux)開發中,Sleep 是 Windows API,delay 多為 Turbo C 古老庫函數,兩者在標準 Linux 頭文件中均不存在。正規做法是使用 POSIX 標準的 usleep(微秒)、nanosleep(納秒)或更高精度的 clock_nanosleep。
| 函數 | 頭文件 | 精度 | 備註 |
|---|---|---|---|
usleep(useconds_t) | <unistd.h> | 微秒 (µs) | POSIX.1-2001,已標記棄用但廣泛可用 |
nanosleep(const struct timespec*, struct timespec*) | <time.h> | 納秒 (ns) | 推薦標準做法,可被信號中斷並返回剩餘時間 |
clock_nanosleep(clockid_t, int, const struct timespec*, struct timespec*) | <time.h> | 納秒 (ns) | 可指定時鐘源(CLOCK_MONOTONIC 避免系統時間調整影響) |
#include <time.h>
#include <errno.h>
void msleep(long ms) {
struct timespec req = { .tv_sec = ms / 1000, .tv_nsec = (ms % 1000) * 1000000 };
struct timespec rem;
while (nanosleep(&req, &rem) == -1 && errno == EINTR) {
req = rem; // 被信號中斷則重新睡眠剩餘時間
}
}
#include <unistd.h>
void usleep_wrapper(unsigned int us) {
while (us > 0) {
unsigned int chunk = us > 1000000 ? 1000000 : us; // usleep 參數上限通常為 1e6
usleep(chunk);
us -= chunk;
}
}
man usleep 顯示「No manual entry」通常是未安裝 manpages-posix 或 manpages-dev,執行 sudo apt install manpages-posix manpages-dev 即可。syscall(SYS_nanosleep, ...) 屬底層調用,應用層請直接呼叫庫函數。PREEMPT_RT 內核或用戶空間自旋。掌握 nanosleep 與 clock_nanosleep 的正確用法,即可在 Ubuntu/Linux 下靈活實現從毫秒到納秒級的精準延時控制。