【发布时间】:2016-09-22 23:23:41
【问题描述】:
我有一个 c 程序 它使用 tcgetattr 和 tcsetattr 来停止回显用户输入。
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
int
main(int argc, char **argv)
{
struct termios oflags, nflags;
char password[64];
/* disabling echo */
tcgetattr(fileno(stdin), &oflags);
nflags = oflags;
nflags.c_lflag &= ~ECHO;
nflags.c_lflag |= ECHONL;
if (tcsetattr(fileno(stdin), TCSANOW, &nflags) != 0) {
perror("tcsetattr");
return EXIT_FAILURE;
}
printf("password: ");
fgets(password, sizeof(password), stdin);
password[strlen(password) - 1] = 0;
printf("you typed '%s'\n", password);
/* restore terminal */
if (tcsetattr(fileno(stdin), TCSANOW, &oflags) != 0) {
perror("tcsetattr");
return EXIT_FAILURE;
}
return 0;
}
我想使用 shell 脚本执行这个程序并给它一些输入。按照here 的步骤我试过了
$ ./test <<EOF
> hello
> EOF
和
$ ./test <<<'hello'
和
$ ./test <input
和
$ cat input | ./test
但以上所有方法都给了我tcsetattr: Inappropriate ioctl for device 错误
运行此类程序并将其添加到 shell 脚本的适当方法是什么? 或者我们可以从 python 运行它吗?如果是,如何将输入从 python 传递给 c 程序?
【问题讨论】:
-
@andlrc 重复的问题要求“检查标准输入是否存在的方法”。在我的程序中存在标准输入,我只是使用 tcgetattr 和 tcsetattr 关闭了回声。
-
#include <unistd.h> int isatty(int fd); -
@wildplasser 你能解释一下吗?我没听懂你在说什么
-
[请先阅读 isatty() 的手册页]
stdin是一个文件。但并非所有文件都具有相同的属性;您的 ioctl 仅对某些类型的文件 (TTY) 有效 这适用于许多文件操作,例如,您无法查找或挂载 tty,也无法设置管道或磁盘文件的波特率。
标签: c bash shell input io-redirection