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