c - 休眠 N 秒并等待按键

标签 c linux nonblocking

我想用 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/

相关文章:

linux - 在 Linux 中写一个脚本在每个最大深度为 2 的子目录中运行 make

linux - ARM 内联汇编 : exit system call with value read from memory

asynchronous - apache http 异步客户端中 I/O 调度程序的数量

javascript - Node.js 是否同时只执行一个上下文?

java - 读取文件时在 Java 中获取权限被拒绝 (Linux)

.net - 是否有 MessageBox.Show 的非阻塞版本(或类似的版本)?

c - 如何在内核中记录大量数据

c - 表示地理表面地形图的二维数组算法

C - 无法在递归函数内进行索引

c - 为什么为 scanf 输入添加多个句点会跳过下一个 scanf 函数?