2016-05-25 2 views
1

私はCプログラムを持っています ユーザ入力のエコーを停止するtcgetattrとtcsetattrを使用します。シェルスクリプトからCプログラムに入力を送信

#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; 
} 

このプログラムをシェルスクリプトを使用して実行し、それに何らかの入力をしたいとします。私は

$ ./test <<EOF 
> hello 
> EOF 

$ ./test <<<'hello' 

$ ./test <input 

$ cat input | ./test 

が、すべてのメソッドの上にしようとしたhereから次の手順では、私を与えたtcsetattr: Inappropriate ioctl for deviceエラー

シェルスクリプトに追加するプログラムを実行する適切な方法は何ですか? または、Pythonから実行できますか?はいの場合は、どのようにPythonからCプログラムに入力を渡すのですか?

+0

@andlrc重複する質問は、「標準が存在するかどうかを確認する方法」を尋ねます。私のプログラムではstdinは存在していますが、tcgetattrとtcsetattrを使ってエコーをオフにしました。 – hiabcwelcome

+1

'#include int isatty(int fd); ' – wildplasser

+0

@wildplasser説明できますか?私はあなたが何を言っているのか理解していません – hiabcwelcome

答えて

0

次のExpectスクリプトは私にとって役に立ちました。

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

次のように私は出力を得た:

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

これが働き、他のではないだろう、なぜ私にはわかりません。 詳しい説明がある場合は、この回答を編集してください。

関連する問題