C ++ Linux Shell - 通过命令向量使用管道,分支和执行

时间:2017-03-14 02:18:57

标签: c++ linux shell vector

我正在用C ++编写Linux shell。我主要担心的是能够无限期地管道命令。例如:

ls | cat -A | cat -A | cat -A

为此,我解析了输入字符串并制作了几个unix_command对象并将它们推送回向量。 unix_command结构提供运行命令所需的信息,如名称和参数。

我需要遍历向量,设置管道以便当前进程从前一个进程获得输入,并继续直到向量结束。我用for循环和一堆dup2命令做这个,但没有运气。截至目前,我正在获得奇怪的无限循环行为。

if(cmdVector.size() > 1){

        int filedes[2]; // filedes[0] is for reading, filedes[1] is for writing.
        pipe(filedes);  //Makes a pipe

        //STARTING OVER ON PIPING
        dup2(0,filedes[1]); // Sets write end of pipe to standard input (keyboard)

        for(unsigned int i = 0; i < cmdVector.size(); i++){
            //Do the piping, fork, and run() operations in here!!
            pid_t pid = fork();
            if(pid == 0){   //Child
                if(i != cmdVector.size() - 1){  //As long as this isn't the last command
                    dup2(filedes[WRITE],1); //Set writes of the process here
                    close(filedes[READ]);
                    close(filedes[WRITE]);
                }
                cmdVector[i].run(); //Runs command and calls exec


            }
            else{
                wait(NULL);
                dup2(filedes[READ],0);  //Set input of the main process here, because it forks into the next process, right?
                close(filedes[READ]);   //So if this loops back around and forks, will the child still have the pipe as its input?
                close(filedes[WRITE]);
            }
        }
        dup2(0,0);  //Resets read and write back to normal, hopefully
        dup2(1,1);
    }
    else{   //Just one process, no piping
        pid_t pid = fork();
        if(pid == 0){   //Child
            cmdVector[0].run();
        }
        else{
            wait(NULL);
        }

    }

任何帮助表示赞赏!谢谢!

完整的shell.cpp文件,如果您想运行它:https://drive.google.com/open?id=0BwN_NTSpWmSzWmMzVEl0UzNDZEk

MakeFile:https://drive.google.com/open?id=0BwN_NTSpWmSzTVNSdWxSQWJzYzA

0 个答案:

没有答案