1. 功能

程序执行过程中,点击键盘p按键(pause), 程序暂停, 点击键盘上的n按键(next),程序继续执行

2. 代码


#include <iostream>
#include <stdio.h>
#include <unistd.h>  
#include <stdlib.h>  
#include <sys/ioctl.h> 

char get_keyboard()
{
    //fd_set 为long型数组
    //其每个元素都能和打开的文件句柄建立联系
    fd_set rfds;
    struct timeval tv;
    char c = '\0';

    //将 rfds数组清零
    FD_ZERO(&rfds);
    //将rfds的第0位置为1,这样fd=1的文件描述符就添加到了rfds中
    //最初 rfds为00000000,添加后变为10000000
    FD_SET(0, &rfds);
    tv.tv_sec = 0;
    tv.tv_usec = 10; //设置等待超时时间

    //检测键盘是否有输入
    //由内核根据io状态修改rfds的内容,来判断执行了select的进程哪个句柄可读
    if (select(1, &rfds, NULL, NULL, &tv) > 0)
    {
        c = getchar();
    }

    //没有数据返回'\0'
    return c;
}

int main(int argc, char **argv)
{
    int tmp = system("stty -icanon");

    for (int i = 0; i < 10000; i++)
    {

        char control_char = get_keyboard();
        std::cout << "control_char: " << control_char << std::endl;
        if (control_char == 'p') // pause
        {
            sleep(1);
            do
            {
                control_char = get_keyboard();
            } while (!(control_char == 'n')); // next
        }

        // do-something
        std::cout << "count: i = " << i << std::endl;
    }
    return 0;
}

可以使用opencv中相关函数简单实现: 空格键暂停, 其它任意键继续:

// ...
int key = cv::waitKey(100) & 0xff;
if (key == 32) //bland
{
   cv::waitKey(0);
}
// ...

参考: linux下实现键盘的无阻塞输入_fd_zero(&rfds);-CSDN博客

拓展: 每隔1秒,for 循环执行一次:

char control_char = '\0';
char slow_char = '\0';

//for循环中:
{       control_char = get_keyboard();        
        // 不区分大小写
        if (control_char >= 'A' && control_char <= 'Z')
            control_char += 32;        
        // 按 l 或者 L, sleep 2秒, 按 n 或者 N, 恢复正常
        if ((control_char == 'l')|| control_char == 'n')
        {
            slow_char = control_char;
            if (slow_char == 'l')
                b_slow = true;
            else if (slow_char == 'n')
                b_slow = false;
        }
        if (b_slow)
        {
            sleep(2);
            std::cout << "sleep(2) second"<< std::endl;
        }

        // do sth ...
}

参考: select() fd_set 原理介绍: [【一文搞懂】FD_SET的使用_欧恩意的博客-CSDN博客](https://blog.csdn.net/Fuel_Ming/article/details/122931926)