目录
一、usleep函数
1、函数介绍
以微妙为单位的睡眠函数。usec:待休眠的微妙数。
#include <unistd.h>
int usleep(useconds_t usec);
2、函数原型
#include <time.h>
#include <unistd.h>
int
usleep (useconds_t useconds)
{
struct timespec ts =
{
.tv_sec = (long int) (useconds / 1000000),
.tv_nsec = (long int) (useconds % 1000000) * 1000ul
};
/* Note the usleep() is a cancellation point. But since we call
nanosleep() which itself is a cancellation point we do not have
to do anything here. */
return __nanosleep (&ts, NULL);
}
二、nanosleep函数
1、函数介绍
以纳秒为单位的休眠函数。
1秒=1000 毫秒 (ms)
1秒=1,000,000 微妙 (μs)
1秒=1,000,000,000 纳秒 (ns)
#include <time.h>
//req: struct timespec类型指针,设置休眠的时间
//rem: 若remain不为NULL,那么指针指向的缓冲区返回剩余的休眠时间
int nanosleep(const struct timespec *req, struct timespec *rem);
timespec结构体原型:
struct timespec {
time_t tv_sec; /* 秒 */
long tv_nsec; /* 纳秒 范围是0-999999999(9个9)*/
};
三、nanosleep实现毫秒级休眠
void mssleep(unsigned long ms)
{
struct timespec ts = {
.tv_sec = (long int) (ms / 1000),
.tv_nsec = (long int) (ms % 1000) * 1000000ul
};
nanosleep(&ts, 0);
}