c - 退出程序后输出执行UNIX命令

标签 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”作为示例,另一个重要的注意事项是我的程序设计为仅处理一个管道,我不支持多管道命令。但是考虑到所有这些,我哪里出错了,我应该怎么做才能修复它以便它在 shell 内输出,而不是在 shell 外输出。非常感谢您提供的所有建议和帮助。

最佳答案

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

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

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

关于c - 退出程序后输出执行UNIX命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58293804/

相关文章:

Git 可以检测两个源文件是否本质上是彼此的副本吗?

Cortex : NVIC,请演示如何通过软件使其电平或边缘检测

linux - 如果两行以相同的表达式开头,则合并文本文件中的两行

linux - 在 shell 脚本中执行 shell 命令时出现问题

shell - Emacs ansi-term 作为登录 shell

linux - select() 在 python2 和 python3 上的行为是否不同?

shell - 带有空格的 scala 进程无法正常工作

使用 C : mocking nested function calls 进行 Cmocka 单元测试

c - 二进制炸弹的汇编代码困惑

perl - 如何在不使用 select 的情况下检查(查看)Perl 中管道数据的 STDIN?