
在Linux中,进程休眠(sleep)是指进程暂停执行一段时间。常用的休眠函数包括sleep、usleep和nanosleep。它们的主要区别在于指定休眠时间的精度。
sleep函数使进程休眠指定的秒数。其原型为:
unsigned int sleep(unsigned int seconds);seconds是进程休眠的时间,以秒为单位。示例如下:
#include <unistd.h>
#include <stdio.h>
int main() {
printf("Sleeping for 5 seconds...\n");
sleep(5);
printf("Awake!\n");
return 0;
}usleep函数使进程休眠指定的微秒数。其原型为:
int usleep(useconds_t usec);usec是进程休眠的时间,以微秒为单位(1秒 = 1,000,000微秒)。示例如下:
#include <unistd.h>
#include <stdio.h>
int main() {
printf("Sleeping for 500,000 microseconds (0.5 seconds)...\n");
usleep(500000);
printf("Awake!\n");
return 0;
}nanosleep函数使进程休眠指定的纳秒数。其原型为:
int nanosleep(const struct timespec *req, struct timespec *rem);参数:
req:指向一个timespec结构体,指定休眠时间。rem:指向一个timespec结构体,如果休眠被信号中断,则此结构体保存剩余的时间。返回值:0表示成功,-1表示失败,并设置errno。
timespec结构体定义如下:
struct timespec {
time_t tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};示例如下:
#include <time.h>
#include <stdio.h>
int main() {
struct timespec req, rem;
req.tv_sec = 0;
req.tv_nsec = 500000000L; // 500 milliseconds
printf("Sleeping for 500,000,000 nanoseconds (0.5 seconds)...\n");
if (nanosleep(&req, &rem) == -1) {
printf("Nanosleep was interrupted\n");
}
printf("Awake!\n");
return 0;
}sleep的精度最低,以秒为单位;usleep以微秒为单位,精度稍高;nanosleep以纳秒为单位,精度最高。这三个函数提供了不同精度和功能的休眠方式,根据实际需求选择合适的函数。
作者:不脱发的程序猿。来源:CSDN 原文(CC BY-SA 4.0)。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。