Linux C select:管道回显输入有效,但从键盘读取无效?

问题描述 投票:0回答:1

我试图理解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;
}

编辑:参见答案;因此我们只需要按 Enter 键即可:

:~$ ./select 

A key was pressed!

或者我们可以使用

stty raw
关闭缓冲输入(然后使用
stty cooked
将其重新打开):

:~ stty raw
:~ ./select 
                                            dA key was pressed!
                                                               :~ stty cooked 
c stdin keypress posix-select
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.