我有一些在 Windows 上编译的源代码。我正在将其转换为在 Red Hat Linux 上运行。
源代码包含
<windows.h>
头文件,程序员使用Sleep()
函数等待一段时间。这在 Linux 上不起作用。
但是,我可以使用
sleep(seconds)
函数,但它以秒为单位使用整数。我不想将毫秒转换为秒。在 Linux 上进行 gcc 编译时,是否可以使用替代的睡眠功能?
是 - 较旧的 POSIX 标准定义
usleep()
,所以这在 Linux 上可用:
int usleep(useconds_t usec);
描述
usleep() 函数暂停调用线程的执行 (至少)usec 微秒。睡眠可能会稍微延长 任何系统活动或处理呼叫所花费的时间或 系统计时器的粒度。
usleep()
需要 microseconds,因此您必须将输入乘以 1000 才能在毫秒内休眠。
usleep()
已被弃用,随后从 POSIX 中删除;对于新代码,首选nanosleep()
:
#include <time.h> int nanosleep(const struct timespec *req, struct timespec *rem);
描述
暂停调用线程的执行,直到至少在nanosleep()
中指定的时间已经过去,或者 传递触发调用处理程序的信号 调用线程或终止进程。*req
结构timespec用于指定纳秒精度的时间间隔。定义如下:
struct timespec { time_t tv_sec; /* seconds */ long tv_nsec; /* nanoseconds */ };
使用
msleep()
实现的nanosleep()
函数的例子,如果被信号打断则继续睡眠:
#include <time.h>
#include <errno.h>
/* msleep(): Sleep for the requested number of milliseconds. */
int msleep(long msec)
{
struct timespec ts;
int res;
if (msec < 0)
{
errno = EINVAL;
return -1;
}
ts.tv_sec = msec / 1000;
ts.tv_nsec = (msec % 1000) * 1000000;
do {
res = nanosleep(&ts, &ts);
} while (res && errno == EINTR);
return res;
}
你可以使用这个跨平台功能:
#ifdef WIN32
#include <windows.h>
#elif _POSIX_C_SOURCE >= 199309L
#include <time.h> // for nanosleep
#else
#include <unistd.h> // for usleep
#endif
void sleep_ms(int milliseconds){ // cross-platform sleep function
#ifdef WIN32
Sleep(milliseconds);
#elif _POSIX_C_SOURCE >= 199309L
struct timespec ts;
ts.tv_sec = milliseconds / 1000;
ts.tv_nsec = (milliseconds % 1000) * 1000000;
nanosleep(&ts, NULL);
#else
if (milliseconds >= 1000)
sleep(milliseconds / 1000);
usleep((milliseconds % 1000) * 1000);
#endif
}
usleep()
,它在 POSIX 2008 中没有定义(尽管它在 POSIX 2004 之前定义,并且显然在 Linux 和其他具有 POSIX 合规历史的平台上可用),POSIX 2008 标准定义了 nanosleep()
:
- 高分辨率睡眠nanosleep
#include <time.h> int nanosleep(const struct timespec *rqtp, struct timespec *rmtp);
函数应使当前线程暂停执行,直到nanosleep()
参数指定的时间间隔过去或信号传递给调用线程,其操作是调用信号捕获功能或终止进程。暂停时间可能比请求的时间长,因为参数值向上舍入为睡眠分辨率的整数倍,或者因为系统调度了其他活动。但是,除了被信号中断的情况外,暂停时间不得小于rqtp
指定的时间,由系统时钟CLOCK_REALTIME测量。rqtp
功能的使用对任何信号的动作或阻塞没有影响nanosleep()
超越 usleep,具有 NULL 文件描述符集的不起眼的 select 将让您以微秒级精度暂停,并且没有
SIGALRM
并发症的风险。
sigtimedwait 和 sigwaitinfo 提供类似的行为。
#include <unistd.h>
int usleep(useconds_t useconds); //pass in microseconds