用c ++实现管道

时间:2015-10-06 15:06:05

标签: c++ pipe exec fork

我试图在C ++中实现管道。我的方法piped沿yes | head -10 | wc行接收一系列参数。它会创建管道数量的流程,并根据该示例将yeshead -10wc更改为流程图像。然后它创建管道2管道并将流程的输入和输出重定向到管道。

它无法正常工作,只需单独打印每个命令,而无需重定向输入/输出。

#include "piped.h"

using namespace std;

void piped(char *stringList[], int pipes)
{

//stringList[] is list of arguments seperated by |
//pipes = number of arguments

pid_t processList[256];
char *curList[256];

//Create a new process for each job using fork

for(int i = 0; i < pipes; i++){
    processList[i] = fork();

    if (processList[i] < 0) {
        cerr << "Couldn't create process\n";
        exit(1);
    }
}

int j = 0;

//Replace the image of each process with the appropriate commands

for(int i = 0; i < pipes; i++){

    pid_t pid = processList[i];

    if(pid == 0){

    char *check = stringList[j];

    int k = 0;

    while(true){

        curList[k] = check;
        j+=1;
        k+=1;

        check = stringList[j];

        if(check == NULL || strcmp(check, "|") == 0){
            break;
        }
    }

    j+=1;

    curList[k] = NULL;

    execvp(curList[0], curList);
    cout << "Exec error!\n";
    exit(1);

    }
}


//Piping
//create n-2 pipes 
//redirect the output of job i to the write end of pipe i
//redirect the input of job i to the read end of pipe i

for(int i = 0; i < pipes-1; i++){

    int pipefd[2];

    if(pipe(pipefd) < 0){
        cout << "Pipe error!\n";
    }

    int pid1 = processList[i];
    int pid2 = processList[i+1];

    if(0 == pid2){
        //Child 2
        close(pipefd[1]);
        dup2(pipefd[0],1);
        close(pipefd[0]);

    }

    if(0 == pid1){
        close(pipefd[0]);
        dup2(pipefd[1], 0);
        close(pipefd[1]);
    }

}

//Wait for all jobs to terminate

for(int i = 0; i < pipes; i++){
    pid_t pid = processList[i];
    waitpid(pid, NULL, 0);
}
}

0 个答案:

没有答案