【发布时间】:2010-11-30 11:39:56
【问题描述】:
在过去的几天里,我一直在尝试编写自己的 shell 实现,但我似乎一直无法让管道正常工作。我能够解析一行并单独分叉管道之间的命令(例如:ls | sort),但似乎无法让它们将输入从一个管道传输到另一个。
我想我只是不明白如何正确使用 dup2() 和管道。
我现在已经包含了我仍然失败的代码... :( 所以卡住了...
void forkAndExecute( char* arrayOfWords[] , vector<pid_t> *vectorOfPIDs , bool hasNextCmd , bool hasPrevCmd) {
int fd[ 2 ];
pid_t pid;
if( hasNextCmd ){
pipe(fd);
}
pid = fork();
//error if PID < 0
if( pid < 0 ) {
cerr << ">>> fork failed >>>" << endl;
exit(-1);
}
//child process if PID == 0
else if( pid == 0 ) {
if ( hasPrevCmd ){
dup2(fd[0] , 0);
close(fd[0]);
close(fd[1]);
}
if ( hasNextCmd ){
dup2(fd[1],1);
close(fd[0]);
close(fd[1]);
}
execvp( arrayOfWords[0] , arrayOfWords );
cout << ">>> command not found >>>" << endl;
//if logic reaches here, exec failed
exit(0);
}
//parent process
else{
close(fd[0]);
close(fd[1]);
//if( ! isLastCmd ){
//}
vectorOfPIDs->push_back(pid);
}
}
【问题讨论】: