使用C ++创建Linux管道

时间:2014-11-08 13:50:01

标签: c++ linux shell pipe

我正在尝试创建一个包含管道和重定向的简单shell程序。对于管道我目前有以下代码:

//****Contains Prompts for User Input outside of 'If' statement********

if( contains(userInput, '|', str1, str2));

//Fork a child process
pid_t pid1 = fork();
if (pid1 == 0) {

//First child creates the pipe
pipe(pipeFD);

    //First child forks to a second child
    pid_t pid2 = fork();
    if(pid2 == 0){

    //Replaces standard output with pipe input
    dup2(pipeFD[1], 1);


    //Executes first command
    parseArgs(str1, argv);
    execvp(argv[0],argv);
    }else{wait(NULL);}

//Back in first child

    //Fork a third child
    pid_t pid3 = fork();
    if(pid3 == 0){

    //Third child replaces standard input with pipe output
    dup2(pipeFD[0],0);

    //Third child executes the second command
    parseArgs(str2, argv);
    execvp(argv[0],argv);
    exit(EXIT_FAILURE);
    }else{wait(NULL);}

  }
}

就目前而言,我一直在使用ls | grep作为我管道的测试。输出应如下所示:

ls|grep hello
hello.cpp
helloworld.cpp
helloworld2.cpp
Enter a command:

相反,它看起来像这样:

ls|grep hello
Enter a command: hello.cpp
helloworld.cpp
helloworld2.cpp

1 个答案:

答案 0 :(得分:0)

好的,我已经弄清楚出了什么问题!原来我试图通过在子进程中嵌套2个子进程来做太多。我已经完善了我的管道流程,只需要父流程中的2个子流程,现在它可以按预期工作:

 //Pass UserInput into the contains function to see if a pipe or redirect was used
if ( contains(userInput, '|')){

  split(userInput, '|', str1, str2);
  pipe(pipeFD);

    //Shell forks first child process
    pid_t pid1 = fork();
    if(pid1 == 0){

//First Child replaces standard output with pipe input
dup2(pipeFD[1],1);

//First Child Executes the first command
parseArgs(str1, argv);
execvp(argv[0],argv);

//Exit if execvp returns
exit(EXIT_FAILURE);
}

//Shell forks second child process
pid_t pid2 = fork();
if (pid2 == 0){

//Second Child replaces standard input with pipe output
    dup2(pipeFD[0],0);

//Second Child Executes the second command
parseArgs(str2, argv);
execvp(argv[0],argv);
exit(EXIT_FAILURE);
}else{wait(0);}

}