0
我想了解http://beej.us/guide/bgnet/examples/select.c(以下內容僅供參考)。我這樣做:Linux 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