重定向输入时C ++简单交互式shell提示隐藏

时间:2015-10-16 14:10:09

标签: c++ shell prompt

我正在用C ++编写一个简单的交互式shell程序。它应该适用于shbash

程序看起来像这样(尽可能简化):

#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 < test.in(重定向输入)运行shell,它会生成带有shell提示的输出:

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

它确实产生了正确的输出(在这种情况下只是输出输入字符串),但它是“poluted&#39;提示。

在重定向输入时,是否有一些相当简单的方法可以摆脱它(如果我对例如bash做同样的事情,输出中没有提示)? 提前谢谢

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:1)

假设您正在运行* NIX类型的系统,您可以(并且应该)使用isatty来测试stdin是否连接到tty(交互式终端)。

这样的事情会起作用:

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