2014-11-08 51 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);} 

}