【问题标题】:Send input to a C program from shell script [duplicate]从shell脚本向C程序发送输入[重复]
【发布时间】: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 &lt;unistd.h&gt; int isatty(int fd);
  • @wildplasser 你能解释一下吗?我没听懂你在说什么
  • [请先阅读 isatty() 的手册页] stdin 是一个文件。但并非所有文件都具有相同的属性;您的 ioctl 仅对某些类型的文件 (TTY) 有效 这适用于许多文件操作,例如,您无法查找或挂载 tty,也无法设置管道或磁盘文件的波特率。

标签: c bash shell input io-redirection


【解决方案1】:

以下 Expect 脚本对我有用。

#!/usr/bin/expect
spawn ./test
expect "password:"
send "hello word\r"
interact

我得到如下输出:

$ ./test.sh 
spawn ./test
password: 
you typed 'hello word'

我不知道为什么这行得通而其他行不通。 如果有人有更多解释,请随时编辑此答案。

【讨论】:

    猜你喜欢
    • 2018-02-11
    • 1970-01-01
    • 2010-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-29
    • 2021-08-22
    • 1970-01-01
    相关资源
    最近更新 更多