【发布时间】:2011-12-08 09:29:45
【问题描述】:
我正在尝试使用从website 获得的教程来实现多个管道。在执行处理多个管道的函数后,我似乎遇到了错误的文件描述符错误。当我第一次欺骗时,它会向我发送此错误。代码如下:
void runPipedCommands(cmdLine* command, char* userInput) {
int numPipes = countPipes(userInput);
int status = 0;
int i = 0, j = 0;
pid_t pid;
int pipefds[2*numPipes];
for(i = 0; i < (numPipes); i++){
if(pipe(pipefds + i*2) < 0) {
perror("pipe");
exit(EXIT_FAILURE);
}
}
j = 0;
while(command) {
pid = fork();
if(pid == 0) {
//if not first command
if(j != 0){
if(dup2(pipefds[j-2], 0) < 0){
perror(" dup2");///j-2 0 j+1 1
exit(EXIT_FAILURE);
}
if(command->next){
printf(
if(dup2(pipefds[j + 1], 1) < 0){
perror("dup2");
exit(EXIT_FAILURE);
}
}
for(i = 0; i < 2*numPipes; i++){
close(pipefds[i]);
}
if( execvp(*command->arguments, command->arguments) < 0 ){
perror(*command->arguments);
exit(EXIT_FAILURE);
}
} else if(pid < 0){
perror("error");
exit(EXIT_FAILURE);
}
command = command->next;
j++;
}
for(i = 0; i < 2 * numPipes; i++){
close(pipefds[i]);
printf("in parent: closed pipe[%d]\n", i);
}
wait(0);
}
}
也许某处有泄漏,或者找不到描述符。我似乎不知道问题出在哪里。我做错了什么?谢谢。
修改后的代码:
void runPipedCommands(cmdLine* command, char* userInput) {
int numPipes = countPipes(userInput);
int status = 0;
int i = 0, j = 0;
pid_t pid;
int pipefds[2*numPipes];
for(i = 0; i < (numPipes); i++){
if(pipe(pipefds + i*2) < 0) {
perror("pipe");
exit(EXIT_FAILURE);
}
}
j = 0;
while(command) {
pid = fork();
if(pid == 0) {
//if not first command
if(j != 0 && j!= 2*numPipes){
if(dup2(pipefds[j-2], 0) < 0){
perror(" dup2");///j-2 0 j+1 1
exit(EXIT_FAILURE);
}
}
//if not last command
if(command->next){
printf("command exists: dup(pipefd[%d], 1])\n", j+1);
if(dup2(pipefds[j + 1], 1) < 0){
perror("dup2");
exit(EXIT_FAILURE);
}
}
for(i = 0; i < 2*numPipes; i++){
close(pipefds[i]);
printf("in child: closed pipe[%d]\n", i);
}
if( execvp(*command->arguments, command->arguments) < 0 ){
perror(*command->arguments);
exit(EXIT_FAILURE);
}
} else if(pid < 0){
perror("error");
exit(EXIT_FAILURE);
}
command = command->next;
j+=2;
}
for(i = 0; i < 2 * numPipes; i++){
close(pipefds[i]);
printf("in parent: closed pipe[%d]\n", i);
}
wait(0);
}
【问题讨论】:
-
你得到什么错误?在哪里?
-
@sarnold:我在
dup2(pipefds[j-2], 0)收到dup2: bad file descriptor。 -
这是相当混乱的代码;我试了一下,但您最好通过
strace(1)、ltrace(1)或gdb(1)运行它,并观察它们的每一步。