2015-10-16 64 views
2

我正在用C++編寫一個簡單的交互式shell程序。它應該工作於shbash的simalary。C++簡單的交互式shell提示在重定向輸入時隱藏

計劃看起來像這樣(簡化儘可能):

#include <iostream> 
#include <string> 

int main(){ 
    std::string command; 

    while (1){ 
     std::cout << "prompt> "; 
     std::getline(std::cin, command); 
     std::cout << command << std::endl; 
     if (command.compare("exit") == 0) break; 
    } 

    return 0; 
} 

它的工作原理與人機交互所需。它會提示用戶寫入命令,shell執行它。

但是,如果我運行shell這樣./shell < test.in(重定向輸入),它產生與外殼輸出的提示是這樣的:

prompt> echo "something" 
prompt> echo "something else" 
prompt> date 
prompt> exit 

它確實能產生正確的輸出(在這種情況下,只輸出輸入的字符串),但它是'提出要求'。

當重定向輸入時,是否有一些相當簡單的方法可以擺脫它(如果我對例如bash做了相同的處理,輸出中沒有提示)? 預先感謝您

+5

http://linux.die.net/man/3/isatty –

回答

1

假設您是* NIX型系統上運行,你可以(也應該)使用isatty測試標準輸入是否連接到一個tty(交互終端)。

像這樣將工作:

if (isatty(STDIN_FILENO)) { 
    std::cout << "prompt> "; 
} // else: no prompt for non-interactive sessions 
1

cheers-and-hth-alf提出的解決方案適用於我。由於

解決方案:

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

int main(){ 
    std::string command; 

    while (1){ 
     if (isatty(STDIN_FILENO)){ 
      std::cout << "prompt> "; 
     } 
     std::getline(std::cin, command); 
     std::cout << command << std::endl; 
     if (command.compare("exit") == 0) break; 
    } 

    return 0; 
}