C++ 我怎样才能使用此程序通过管道传输多个命令?C++;

C++ 我怎样才能使用此程序通过管道传输多个命令?C++;,c++,shell,pipe,C++,Shell,Pipe,我找到了我目前的一项作业的解决方案。但这是我第一次使用C++中的管道。所以我对这一切还是比较陌生的。我很好奇,如果我想改变这个程序,使其能够处理多个管道,我如何才能准确地计算出有多少管道?我知道ptr变量是一个令牌,但是命令不是在解析时执行的吗?在执行之前,我如何计算所有管道的数量?我希望能够执行这样的任务,直到最后 cat text.txt | sort | tail -3 | grep thankyou 假设您在std::string中有这一行: using Command = std::

我找到了我目前的一项作业的解决方案。但这是我第一次使用C++中的管道。所以我对这一切还是比较陌生的。我很好奇,如果我想改变这个程序,使其能够处理多个管道,我如何才能准确地计算出有多少管道?我知道ptr变量是一个令牌,但是命令不是在解析时执行的吗?在执行之前,我如何计算所有管道的数量?我希望能够执行这样的任务,直到最后

cat text.txt | sort | tail -3 | grep thankyou

假设您在
std::string
中有这一行:

using Command = std::vector<std::string>;
using Pipeline = std::vector<Command>;

Pipeline p;
Command c;
std::istringstream iss(line);
while (true) {
  std::string token;
  iss >> token;
  if (iss.eof()) {
    // Nothing more to read. Push the last command to the pipeline, if any.
    if (!c.empty()) {
      p.push_back(c);
    }
    break;
  }

  if (token == '|') {
    // We saw a pipe. Push the current command to the pipeline and
    // start parsing a new one.
    p.push_back(c);
    c.clear();
  } else {
    // This is a regular part of a command
    c.push_back(token);
  }
}

这比一开始看起来要复杂一些。应遵守以下几条规则:

  • 管道字符不能后跟其自身(否则它们将构成
    |
    运算符)

  • 记住逃跑

  • 2a。其中弦是最邪恶的

    比如说,我们可以实现一个部分功能的版本

    std::string命令{“cat text.txt | sort | tail-3 | grep thankyou”};
    std::size\u t count{};
    for(auto pos=command.find\u first\u of(“\\\\”)”);pos!=command.npos;
    pos=命令。首先查找(“\\\\”,pos+1))
    {
    开关(命令[pos]){
    //管道字符后面不跟管道字符实际上就是我们要找的
    大小写“|”:如果(pos
    find_closing
    应使用带引号的字符串(如果有)

    std::string::size\u type find\u closing(std::string const&cmd,std::size\u t pos){
    对于(auto nxt=cmd.find_first_of(“\”\”,pos+1);nxt!=cmd.npos;
    nxt=cmd.find\u first\u of(“\”\ \”,nxt+2))
    {
    if(cmd[nxt]==''“')返回nxt;//未转换的结束双引号
    }
    返回cmd.npos;
    }
    
    可能需要一些调试


    此代码不处理非常复杂的情况,例如
    echo“$(echo 123 | sed's/2/4/”)

    答案是“将输入正确地解析为表示管道的对象”对于初学者,你可以在代码> > <代码>字符上进行拆分,并将结果列表中的每个元素作为流水线中的命令来处理。问题头+它的内容和在该问题中提供的引用似乎与C++有关,删除了C标记。
    [
      ["cat", "text.txt"],
      ["sort"],
      ["tail", -3],
      ["grep", "thankyou"]
    ]