2013-10-01 54 views
0

我正在为我的外壳实现多管道。代码的问题在于它不会将我最后一条命令的输出打印到我的标准输出中。有人可以帮忙吗? executePipedCommands函数接受指向命令列表头的指针多管道实施。不工作

我插入例如ls | more | grep s到我的命令列表。

struct cmd_t { 
int nargs, maxargs;  
char **args;   
struct cmd_t *next; 
}; 
typedef struct cmd_t *Cmd; 
void executePipedCommands(Cmd command) { 

    int numPipes = -1; 
    Cmd temp = command; 
    int status; 
    int i = 0; 
    pid_t pid; 

    while(command!= NULL) 
    { 
     numPipes ++; 
     command = command->next; 
    } 
    printf("number of pipes : %d",numPipes); 


    int pipefds[2*numPipes]; 

    for(i = 0; i < (numPipes); i++){ 
     if(pipe(pipefds + i*2) < 0) { 
      perror("couldn't pipe"); 
      exit(EXIT_FAILURE); 
     } 
    } 


    int j = 0; 
    while(command) 
    { 
     pid = fork(); 
     if(pid == 0) 
     { 

      //if not last command 
      if(command->next) 
      { 
       if(dup2(pipefds[j + 1], 1) < 0) 
       { 
        perror("dup2"); 
        exit(EXIT_FAILURE); 
       } 
      } 

      //if not first command&& j!= 2*numPipes 
      if(j != 0) 
      { 
       if(dup2(pipefds[j-2], 0) < 0) 
       { 
        perror(" dup2");///j-2 0 j+1 1 
        exit(EXIT_FAILURE); 

       } 
      } 


      for(i = 0; i < 2*numPipes; i++) 
      { 
        close(pipefds[i]); 
      } 

      if(execvp(*command->args, command->args) < 0) 
      { 
        perror(*command->args); 
        exit(EXIT_FAILURE); 
      } 
     } 
     else if(pid < 0) 
     { 
      perror("error"); 
      exit(EXIT_FAILURE); 
     } 

     command = command->next; 
     j+=2; 
    } 
    /**Parent closes the pipes and wait for children*/ 

    for(i = 0; i < 2 * numPipes; i++){ 
     close(pipefds[i]); 
    } 

    for(i = 0; i < numPipes + 1; i++) 
     wait(&status); 

} 

回答

0

您的代码通过链表步骤,开始command,当它到达终点,以计算所需管道的数量停止。不幸的是,您不会将列表重新设置为起点,因此您无法逐步执行列表以执行命令,因为您已经处于最后。

你大概意思写:

int numPipes = -1; 
Cmd temp = command; 

while (temp != NULL) 
{ 
    numPipes++; 
    temp = temp->next; 
} 
printf("number of pipes: %d\n", numPipes); 

变量temp是其他未使用。或者你可以写:

int numPipes = -1; 
Cmd temp = command; 

while (command != NULL) 
{ 
    numPipes++; 
    command = command->next; 
} 
printf("number of pipes: %d\n", numPipes); 

command = temp;