C 语言中是否有替代毫秒的睡眠函数?
我有一些在 Windows 上编译的源代码。 我正在将其转换为在 Red Hat Linux 上运行。
源代码包含
头文件,并且程序员使用 Sleep()
函数等待一段毫秒时间。 这在 Linux 上不起作用。
但是,我可以使用 sleep(seconds)
函数,但它使用以秒为单位的整数。 我不想将毫秒转换为秒。 有没有可以在 Linux 上与 gcc 编译一起使用的替代睡眠函数?
I have some source code that was compiled on Windows. I am converting it to run on Red Hat Linux.
The source code has included the <windows.h>
header file and the programmer has used the Sleep()
function to wait for a period of milliseconds. This won't work on the Linux.
However, I can use the sleep(seconds)
function, but that uses integer in seconds. I don't want to convert milliseconds to seconds. Is there a alternative sleep function that I can use with gcc compiling on Linux?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用这个跨平台功能:
You can use this cross-platform function:
或者
usleep()
,即POSIX 2008 中没有定义(尽管它是在 POSIX 2004 之前定义的,并且显然可以在 Linux 和其他具有 POSIX 合规历史的平台上使用),POSIX 2008 标准定义了nanosleep()
:Alternatively to
usleep()
, which is not defined in POSIX 2008 (though it was defined up to POSIX 2004, and it is evidently available on Linux and other platforms with a history of POSIX compliance), the POSIX 2008 standard definesnanosleep()
:除了usleep之外,谦虚的select 与 NULL 文件描述符集将让您以微秒精度暂停,并且没有
SIGALRM并发症。
sigtimedwait 和 sigwaitinfo 提供类似的行为。
Beyond usleep, the humble select with NULL file descriptor sets will let you pause with microsecond precision, and without the risk of
SIGALRM
complications.sigtimedwait and sigwaitinfo offer similar behavior.
是 - 较旧的 POSIX 标准定义
usleep()
,因此这在 Linux 上可用:usleep()
需要微秒,因此您必须将输入乘以 1000 才能以毫秒为单位休眠。usleep()
已被弃用并随后从 POSIX 中删除; 对于新代码,nanosleep()
是首选:使用
nanosleep()
实现的示例msleep()
函数,如果被信号中断则继续睡眠:Yes - older POSIX standards defined
usleep()
, so this is available on Linux:usleep()
takes microseconds, so you will have to multiply the input by 1000 in order to sleep in milliseconds.usleep()
has since been deprecated and subsequently removed from POSIX; for new code,nanosleep()
is preferred:An example
msleep()
function implemented usingnanosleep()
, continuing the sleep if it is interrupted by a signal: