连接n个管道linux

时间:2018-09-09 23:08:12

标签: c++ linux pipe

我最近正在研究管道,看到了这个答案:

Connecting n commands with pipes in a shell?

我对此很感兴趣,并尝试制作一个“动态”的字符串,其中我引入了一个带有n个进程的字符串,然后执行了n个进程(即ls | sort)。我试图标记化,保存在数组中,但是没有用。这是我的“令牌生成器”代码:

int main()
{
  char str[] = "ls | sort";
  int length = (sizeof(str) / sizeof(*str))-1;
  int sizeCMD = 1; //If the string has zero pipe, it means it has at least 1 process
  vector<char> tempV;
  for (int i = 0; i < length; i++)
  {
    if (str[i] == '|')
    {//If the string has one |, it means it has at least 2 process.
      sizeCMD++;
    }
    tempV.push_back(str[i]);//I was going to do something else with this, but I forgot.
    //cout<<i<<" "<<tempV.at(i)<<endl;
  }
  int j = 0;//Current position of the cmd

  string comLetter = "";//it will save every single letter in certain conditions

  string comLine = "";//it will save all the characters of comLetter in certain conditions

  struct command cmd[sizeCMD];
  const char *ls[2];
  const char *sort[2];
  const char *toCChar;
  for (int i = 0; i < tempV.size(); i++)
  {
    if (tempV.at(i) != ' ' && tempV.at(i) != '|')
    {//comLetter will only save characters that are not equal to blank or |.
      //cout<<tempV.at(i);
      comLetter += tempV.at(i);
      //cout<< comLetter <<endl;
    }

    if (tempV.at(i) == ' ' || i == tempV.size() - 1)
    {//comLine will save everything of comLetter when it detects a blank or the very end
      //cout<<comLetter<<endl;
      comLine = comLetter;
      comLetter = "";
    }

    if (tempV.at(i) == '|' || i == tempV.size() - 1)
    {//cmd will save everything of comLine when it detects a | or the very end.
      //cout<<j<<endl;
      cout << "." << comLine << "." << endl;
      //cout<<i<<endl;

      //cout<<toCChar<<endl;

      if(comLine == "ls"){
        toCChar = comLine.c_str();
        ls[0] = toCChar;
        ls[1] = 0;  //THIS IF
        cmd[0] = {ls};                 //WORKS
      }

      if(comLine == "sort"){
        sort[0] = "sort";
        sort[1] = 0;  //THIS IF
        cmd[1] = {sort};                 //WORKS
      }

      /*const char *ls[2];
      cout<<toCChar<<endl;
      ls[0] = toCChar;
      ls[1] = 0;
      cout<< *ls[0] << " - "<< endl;
      cmd[j] = {ls};
      //cout << cmd << endl;
      comLine = "";*/
      j++; //The position will move by one.
    }
  }

  return fork_pipes(sizeCMD, cmd);
}

一切对我来说都是有意义的,直到我发现const char*不可能是暂时的,因为它需要数据,所以我需要为2个命令创建2个const char *数组。这就是为什么我有两个数组:*sort[]*ls[],用于排序和ls。

此外,我想知道为什么这些行会被“忽略”:

toCChar = comLine.c_str();
ls[0] = toCChar;

我现在正在挣扎,如果有人可以帮助/指导我如何做,

0 个答案:

没有答案