2013-03-01 21 views
0

假設我有以下短程序,我將其稱爲Parent.c如何從父進程寫入getpass()輸入?

#include <unistd.h> 
#include <stdio.h> 
#include <string.h> 

int main(){ 
    char buffer[100]; 
    memset(buffer, '\0', 100); 
    scanf("%s", buffer); 
    printf("%s\n", buffer); 

    FILE* child = popen("./child","w"); 
    fwrite(buffer, 1, strlen(buffer), child); 
    pclose(child); 

} 

現在有兩種情況child.c

案例1:

#include <unistd.h> 
#include <stdio.h> 
#include <string.h> 

int main(){ 
    char buffer[100]; 
    memset(buffer, '\0', 100); 
    scanf("%s", buffer); 
    printf("%s\n", buffer); 
} 

案例2:

#include <unistd.h> 
#include <stdio.h> 
#include <string.h> 

int main(){ 
    char* password = getpass(""); 
    printf("%s\n", password); 

} 

萬一一個,如果我跑./Parent,然後鍵入的 「Hello World」,我得到的 「Hello World」 兩個回聲。一個來自子項目,另一個來自父項目。

在情況2中,如果我運行./Parent,然後鍵入「Hello World」,我會得到一個「Hello World」的回顯,然後從子進程獲取輸入提示。 如果我在這個提示中輸入「Goodbye」,我會聽到「Goodbye」的回聲。

如何修改Parent.c以獲得與案例1中當前發生的案例2中相同的行爲?

回答

1

簡單的答案是:你不能。

getpass manual page

將getpass()函數打開/dev/tty(該過程的控制終端),輸出該字符串提示關閉回送,讀取一條線( 「密碼」) ,恢復終端狀態並再次關閉/dev/tty

這意味着它直接從終端設備讀取,而不是從標準輸入讀取。

+1

如果從/ dev/tty的讀取,是有一些黑客,使家長寫來的tty讀取,或具有父誘騙兒童到行爲,好像之前的/ dev/tty的實際上是一個管父控制? – merlin2011 2013-03-01 07:25:46

+0

@ merlin2011不是,'/ dev/tty'只是_current_進程的終端。事先不能知道它真的會是哪個僞終端。你可能不得不重新思考你的想法,特別是(也來自'getpass'手冊頁):「這個函數已經過時了,不要使用它。」 – 2013-03-01 07:33:07

+0

它是什麼現代等價物? – merlin2011 2013-03-01 07:37:34