2014-11-08 55 views
0

我想创建一个包含管道和重定向的简单shell程序。对于管道目前,我有以下代码:使用C++创建Linux管道

//****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 
+0

研究现有的Linux壳:大部分是免费软件,所以你应该下载并研究源代码(例如[bash的](https://www.gnu.org/software/bash/)...)。你也可以使用'strace'。另请阅读[高级Linux编程](http://advancedlinuxprogramming.com/) – 2014-11-08 13:52:29

+0

只有部分资源,目前还不清楚你的程序在做什么。此外,'ls'和'grep'都是现有的程序,您希望如何调用您的程序也不清楚。 – 2014-11-08 14:14:44

+0

就我所见,主程序在输出“输入命令”之前不会“等待”儿童。 – 2014-11-08 15:11:21

回答

0

好,我已经想通了,什么是错的!原来我试图通过嵌套在子进程中的两个子进程来做太多事情。人有我精我的管道过程只需要父进程中的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);} 

}