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
研究现有的Linux壳:大部分是免费软件,所以你应该下载并研究源代码(例如[bash的](https://www.gnu.org/software/bash/)...)。你也可以使用'strace'。另请阅读[高级Linux编程](http://advancedlinuxprogramming.com/) – 2014-11-08 13:52:29
只有部分资源,目前还不清楚你的程序在做什么。此外,'ls'和'grep'都是现有的程序,您希望如何调用您的程序也不清楚。 – 2014-11-08 14:14:44
就我所见,主程序在输出“输入命令”之前不会“等待”儿童。 – 2014-11-08 15:11:21