Я пытаюсь создать простую программу оболочки, которая включает в себя каналы и перенаправления. Для трубопроводов в настоящее время у меня есть следующий код:
//****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
Хорошо, я понял, что случилось! Оказывается, я пытался сделать слишком много, имея 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);}
}
strace
. Читайте также Расширенное программирование в Linuxls
иgrep
являются обеими существующими программами, и то, как вы собираетесь вызывать вашу программу с этим, также неясно.