我退出程序后正在输出UNIX命令的执行

时间:2019-10-08 20:40:43

标签: c shell pipe stdout stdin

由于某种未知的原因,当我在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”作为示例,另一个重要说明是我的程序仅设计用于处理一个管道,不支持多管道命令。但是考虑到所有这些,我在哪里出错了,我应该怎么做才能对其进行修复,以使其在外壳内而不是外壳内输出。在此先感谢您提供的所有建议和帮助。

1 个答案:

答案 0 :(得分:1)

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

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

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