退出程序后输出UNIX命令的执行结果

问题描述 投票:1回答:1

由于某种未知的原因,当我在Shell程序中执行管道命令时,它们仅在我退出程序后才输出,有人知道为什么吗?

代码:

int execCmdsPiped(char **cmds, char **pipedCmds){

  // 0 is read end, 1 is write end 
  int pipefd[2]; 

  pid_t pid1, pid2; 

  if (pipe(pipefd) == -1) {
    fprintf(stderr,"Pipe failed");
    return 1;
  } 
  pid1 = fork(); 
  if (pid1 < 0) { 
    fprintf(stderr, "Fork Failure");
  } 

  if (pid1 == 0) { 
  // Child 1 executing.. 
  // It only needs to write at the write end 
    close(pipefd[0]); 
    dup2(pipefd[1], STDOUT_FILENO); 
    close(pipefd[1]); 

    if (execvp(pipedCmds[0], pipedCmds) < 0) { 
      printf("\nCouldn't execute command 1: %s\n", *pipedCmds); 
      exit(0); 
    }
  } else { 
    // Parent executing 
    pid2 = fork(); 

    if (pid2 < 0) { 
      fprintf(stderr, "Fork Failure");
      exit(0);
    }

    // Child 2 executing.. 
    // It only needs to read at the read end 
    if (pid2 == 0) { 
      close(pipefd[1]); 
      dup2(pipefd[0], STDIN_FILENO); 
      close(pipefd[0]); 
      if (execvp(cmds[0], cmds) < 0) { 
        //printf("\nCouldn't execute command 2...");
        printf("\nCouldn't execute command 2: %s\n", *cmds);
        exit(0);
      }
    } else {
      // parent executing, waiting for two children
      wait(NULL);
    } 
  }
}

输出:

Output of program when I enter "ls | sort -r" for example

在输出的此示例中,我以“ ls | sort -r”作为示例,另一个重要说明是我的程序设计为仅处理一个管道,我不支持多管道命令。但是考虑到所有这些,我要去哪里错了,我应该怎么做才能对其进行修复,以使其在外壳内而不是外壳内输出。预先非常感谢您提供的所有建议和帮助。

c shell pipe stdout stdin
1个回答
0
投票

原因是您的父流程文件描述符尚未关闭。当您等待第二个命令终止时,它会挂起,因为未关闭写入端,因此它将等待直到写入端关闭或有新数据可供读取。

在等待进程终止之前尝试同时关闭pipefd[0]pipefd[1]。>>

还请注意,当一个进程终止时,wait(NULL);将立即返回,如果您的进程之后仍在运行,您将需要第二个以免产生僵尸。

© www.soinside.com 2019 - 2024. All rights reserved.