将分叉进程输出重定向到C中的父进程

时间:2010-10-01 01:13:48

标签: c fork stdout stdin pipe

我正在实现的是bash的(更简单)版本。其中一项任务是接受命令:

$ bg <command> <arguments>

然后,这将分叉一个新流程,然后使用execvp()<command>作为参数在新流程中运行<arguments>。问题是,当我从子进程捕获输出时,我使用pipe(),在从子进程获取输出并在我想要的时候输出它之后,我似乎无法切换回{{1对于我的父(shell)进程,下次我需要接受输入时会导致段错误。

这是我的“bg”功能的一部分。

STDIN

当进程结束后我从管道获取输出的代码。

ChildPID = fork();
if (ChildPID < 0) {
 /* There is an error */
 printf("Error forking the process.\n");
 exit(1);
}
if (ChildPID >= 0) {
 if (ChildPID == 0) {  /* Child Process */
  close(m_pipefd[0]);
  dup2(m_pipefd[1], STDOUT_FILENO);
  close(m_pipefd[1]);
  //sleep(5);
         err = execvp(optionsPTR[0], optionsPTR);
  switch (errno) {
   case ENOENT:
    printf("RSI: %s: command not found\n", optionsPTR[0]);
    break;
   case EACCES:
    printf("RSI: %s: Permission denied\n", optionsPTR[0]);
    break;
  }
  exit(1);
 }
 else {  /* Parent Process */
  WaitErr = waitpid(ChildPID, &status, WNOHANG | WUNTRACED);
                return(0); /* to main */
        }
}
return 0;

所以tl; dr版本是我需要在捕获子进程输出后重置回父进程的stdin。

谢谢,

布雷登

1 个答案:

答案 0 :(得分:3)

通常不需要在父母中混淆stdin和stdout。将中的管道连接到stdin和stdout后,管道的另一端应该能够发送数据或从子项获取数据。

请阅读您父母的m_pipefd [1]。