我有一些在Windows上编译的源代码.我正在将其转换为在Red Hat Linux上运行.
源代码包含<windows.h>头文件,程序员使用该Sleep()函数等待一段时间.这不适用于Linux.
但是,我可以使用该sleep(seconds)函数,但在几秒钟内使用整数.我不想将毫秒转换为秒.有没有替代睡眠功能,我可以在Linux上使用gcc编译?
caf*_*caf 163
是 - 定义了较旧的POSIX标准usleep(),因此可在Linux上使用:
Run Code Online (Sandbox Code Playgroud)int usleep(useconds_t usec);描述
usleep()函数暂停执行调用线程(至少)usec微秒.任何系统活动或处理呼叫所花费的时间或系统定时器的粒度都可以略微延长睡眠时间.
usleep()需要微秒,因此您必须将输入乘以1000才能以毫秒为单位进行休眠.
usleep()自那时起被弃用并随后从POSIX中删除; 对于新代码,nanosleep()首选:
Run Code Online (Sandbox Code Playgroud)#include <time.h> int nanosleep(const struct timespec *req, struct timespec *rem);描述
nanosleep()暂停执行调用线程,直到至少指定的时间*req已经过去,或者传递一个信号,该信号触发调用线程中的处理程序的调用或终止进程.结构timespec用于指定具有纳秒精度的时间间隔.它的定义如下:
Run Code Online (Sandbox Code Playgroud)struct timespec { time_t tv_sec; /* seconds */ long tv_nsec; /* nanoseconds */ };
Ber*_*mos 43
您可以使用此跨平台功能:
#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
usleep(milliseconds * 1000);
#endif
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*ler 31
另外usleep(),在POSIX 2008中没有定义(尽管它定义为POSIX 2004,并且它显然可以在Linux和其他具有POSIX兼容性历史的平台上使用),POSIX 2008标准定义nanosleep():
nanosleep- 高分辨率睡眠Run Code Online (Sandbox Code Playgroud)#include <time.h> int nanosleep(const struct timespec *rqtp, struct timespec *rmtp);该
nanosleep()函数将导致当前线程暂停执行,直到rqtp参数指定的时间间隔已经过去或者信号被传递给调用线程,并且其动作是调用信号捕获函数或终止进程.暂停时间可能比请求的时间长,因为参数值被舍入到睡眠分辨率的整数倍或者由于系统调度其他活动.但是,除了被信号中断的情况外,暂停时间不应小于rqtp由系统时钟CLOCK_REALTIME测量的时间.使用该
nanosleep()功能对任何信号的动作或阻塞都没有影响.
pil*_*row 24
除了usleep之外,使用NULL文件描述符集的简单选择将让您以微秒精度暂停,并且没有SIGALRM并发症的风险.
sigtimedwait和sigwaitinfo提供类似的行为.
小智 13
#include <unistd.h>
int usleep(useconds_t useconds); //pass in microseconds
Run Code Online (Sandbox Code Playgroud)