我想用 C 语言编写一个程序,它执行一些功能然后休眠几分钟。 在此 sleep 期间,我想做一些事情并在按下某个键时退出。
int main()
{
while(1)
{
/*body*/
sleep(300);
}
/*some lines here*/
return 0;
}
无论如何,我可以在 sleep 期间或在任何时候使用非阻塞键监听器退出循环吗?
最佳答案
只是不要休眠 300 秒,而是 300 x 1 秒并检查按键:
int main()
{
while(1)
{
/*body*/
for ( int i=0; i<300; i++ )
{
if (keypressed())
doSomething();
}
}
/*some lines here*/
return 0;
}
编辑:为什么在您的代码中使用 while (1)
?你真的想无休止地运行你的程序吗? (在那种情况下,/*some lines here*/
没有意义。)
关于c - 休眠 N 秒并等待按键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25117476/