0
我现在正在使用下面的函数。但我需要改进的是它会从键盘读取输入(在终端上),即使它没有被按下。我需要知道它何时未被按下(空闲),以便switch case
块将落入default
部分。此时,read()
函数会等待用户输入。任何人都可以给出一个建议,只是基于修改以下代码? 注意:我是一名Java程序员,仍在学习C/C++,因此可能很难让我有点头脑。谢谢你们..非阻塞键盘读取 - C/C++
编辑:我发现这个链接,似乎有什么我想找的东西在fcntl(STDIN_FILENO,F_SETFL,flags | O_NONBLOCK);
行。但是因为我几乎不知道C中的任何内容,所以我完全不知道它在说什么。
http://www.codeguru.com/forum/showthread.php?t=367082
int kfd = 0;
struct termios cooked, raw;
char c;
bool dirty = false;
//get the console in raw mode
tcgetattr(kfd, &cooked);
memcpy(&raw, &cooked, sizeof(struct termios));
raw.c_lflag &=~ (ICANON | ECHO);
// Setting a new line, then end of file
raw.c_cc[VEOL] = 1;
raw.c_cc[VEOF] = 2;
tcsetattr(kfd, TCSANOW, &raw);
puts("Reading from keyboard");
puts("=====================");
puts("Use arrow keys to navigate");
while(true){
//get the next event from the keyboard
if(read(kfd, &c, 1) < 0)
{
perror("read():");
exit(-1);
}
linear_ = angular_ = 0;
ROS_DEBUG("value: 0x%02X\n", c);
switch(c)
{
case KEYCODE_L:
ROS_DEBUG("LEFT");
angular_ = -1.0;
dirty = true;
break;
case KEYCODE_R:
ROS_DEBUG("RIGHT");
angular_ = 1.0;
dirty = true;
break;
case KEYCODE_U:
ROS_DEBUG("UP");
linear_ = 1.0;
dirty = true;
break;
case KEYCODE_D:
ROS_DEBUG("DOWN");
linear_ = -1.0;
dirty = true;
break;
default:
ROS_DEBUG("RELEASE");
linear_ = 0;
angular_ = 0;
dirty = true;
break;
}
而不是直接使用termios的,我建议使用类似[ncurses的(HTTP://en.wikipedia .ORG /维基/ Ncurses的)。 [Here](http://hughm.cs.ukzn.ac.za/~murrellh/os/notes/ncurses.html)是一个教程,展示了如何以非阻塞的方式获取密钥。 – 2012-02-24 10:37:48
仅仅修改上面的代码是没有办法的吗?我只是想从终端读取键盘输入(忘记提及)。当然,我最后的手段是学习
ncurses
,但我已经很难学习C/C++。 – 2012-02-24 10:47:06@JoachimPileborg我编辑了我的问题(我认为是)相关的链接。你认为你知道它在说什么吗? – 2012-02-24 10:53:40