【问题标题】:Linux C select: piping echo to input works, but reading from keyboard doesn't?Linux C 选择:管道回显输入工作,但从键盘读取不?
【发布时间】:2010-05-06 09:42:19
【问题描述】:

我想了解http://beej.us/guide/bgnet/examples/select.c(包含在下面以供参考)。我正在这样做:

:~$ cat /etc/issue

Ubuntu 10.04 LTS \n \l
:~$ gcc --version
gcc (Ubuntu 4.4.3-4ubuntu5) 4.4.3

:~$ wget http://beej.us/guide/bgnet/examples/select.c
:~$ gcc select.c -o select

:~$ echo "ff" | ./select 
A key was pressed!

:~$ ./select 
TYPINGTYTimed out.

因此,选择程序显然将回声管道识别为输入;但它不会识别终端上的按键。为什么是这样?是否可以使用某种重定向(我猜,类似于屏幕如何将键盘输入“重定向”到串行会话)以便识别终端中的实际按键?

谢谢, 干杯!

select.c:

/* ** select.c -- a select() demo */

#include <stdio.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>

#define STDIN 0  // file descriptor for standard input

int main(void)
{
 struct timeval tv;
 fd_set readfds;

 tv.tv_sec = 2;
 tv.tv_usec = 500000;

 FD_ZERO(&readfds);
 FD_SET(STDIN, &readfds);

 // don't care about writefds and exceptfds:
 select(STDIN+1, &readfds, NULL, NULL, &tv);

 if (FD_ISSET(STDIN, &readfds))
  printf("A key was pressed!\n");
 else
  printf("Timed out.\n");

 return 0;
}



编辑:见答案;因此我们只需要按回车键:

:~$ ./select 

A key was pressed!

或者我们可以用stty raw关闭缓冲输入(然后用stty cooked重新打开):

:~ stty raw
:~ ./select 
                                            dA key was pressed!
                                                               :~ stty cooked 

【问题讨论】:

    标签: c select stdin keypress


    【解决方案1】:

    标准输入是一个缓冲流。 select() 调用将无法检测到有可用的输入,直到在输入末尾点击换行符。您不能像这样使用 select() 来读取单个击键。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-16
      • 2018-02-15
      相关资源
      最近更新 更多