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,添加后变为10000000FD_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-somethingstd::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博客