【发布时间】:2014-11-08 13:50:00
【问题描述】:
我正在尝试创建一个包含管道和重定向的简单 shell 程序。对于管道,我目前有以下代码:
//****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 shell:大多数是免费软件,所以你应该下载并研究源代码(例如bash...)。你也可以使用
strace。另请阅读Advanced Linux Programming -
目前还不清楚您的程序在做什么,仅给出部分来源。此外,
ls和grep都是现有程序,您希望如何调用您的程序也不清楚。 -
据我所知,主程序在输出
Enter a command之前并没有为孩子们提供wait -
Geza Torok - 这也是我得出的结论,但是我不确定在哪里放置 wait() 来解决这个问题。