在 C 中等待/暂停几秒钟 [英] Wait/Pause an amount of seconds in C
问题描述
我编写了一个小控制台应用程序,我希望它在循环(一段时间)再次开始之前暂停特定秒数.
I wrote a little console application, and I want it to pause for a certain number of seconds before the cycle (a while) starts again.
我正在使用 Windows 操作系统.
I'm working on Windows operating system.
推荐答案
在 Windows 上,执行此操作的函数是 Sleep
,它需要毫秒的时间睡觉.要使用 Sleep
,您需要包含 windows.h
.
On Windows, the function to do this is Sleep
, which takes the amount of milliseconds you want to sleep. To use Sleep
, you need to include windows.h
.
在 POSIX 系统上,函数 sleep
(来自 unistd.h
)完成了这个:
On POSIX-Systems, the function sleep
(from unistd.h
) accomplishes this:
unsigned int sleep(unsigned int seconds);
DESCRIPTION
sleep() makes the calling thread sleep until
seconds seconds have elapsed or a signal arrives which is not ignored.
如果被信号中断,则返回剩余的休眠时间.如果您使用信号,更可靠的解决方案是:
If it is interrupted by a signal, the remaining time to sleep is returned. If you use signals, a more robust solution would be:
unsigned int time_to_sleep = 10; // sleep 10 seconds
while(time_to_sleep)
time_to_sleep = sleep(time_to_sleep);
这当然是假设您的信号处理程序只需要很少的时间.(否则,这将延迟主程序比预期更长的时间)
This is of course assuming your signal-handlers only take a negligible amount of time. (Otherwise, this will delay the main program longer than intended)
这篇关于在 C 中等待/暂停几秒钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!