我正在尝试使用来自 beej 的 select() 来理解程序。
当我按下一个键时,程序打印“A key was pressed”。但是,程序退出后,相同的键在终端上回显,我收到错误“找不到命令”。为什么按下的键被回显到终端?
源代码:
/*
* select.c demo
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#define STDIN 0
int main(int argc, char *argv[]){
struct timeval tv;
fd_set readfds;
tv = (struct timeval){0};
tv.tv_sec = 2;
tv.tv_usec = 5000000;
FD_ZERO(&readfds);
FD_SET(STDIN, &readfds);
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;
}
输出:
shilpa@shilpa-VirtualBox:Socket_Programming$
shilpa@shilpa-VirtualBox:Socket_Programming$ ./select
f
A key was pressed
shilpa@shilpa-VirtualBox:Socket_Programming$ f
f: command not found
最佳答案
您的程序不使用其 stdin
中的任何内容.
它只检查是否从 stdin
读取会在规定的时间内成功。
因此,就输入消耗而言,它的行为如下:
$ sleep 2.5
如果您运行它并输入 f<enter>
, 然后使用默认终端设置(可通过 stty
控制)它得到回显(终端通常回显您键入的所有内容,除非您将其关闭,例如,对于密码输入),然后在 sleep
时重新回显在您的 shell 收到它时终止。然后 shell 执行 shell 执行的操作——尝试执行它。这失败了,导致 command not found
错误信息。
关于c - 为什么用户的输入会在终端上回显?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38029346/