【问题标题】:Redirecting forked process output to parent process in C将分叉的进程输出重定向到C中的父进程
【发布时间】:2010-10-01 01:13:47
【问题描述】:

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

$ bg <command> <arguments>

这将派生一个新进程,然后使用&lt;command&gt;&lt;arguments&gt; 作为参数在新进程中运行execvp()。问题是,当我从子进程捕获输出时,我使用pipe(),在从子进程获取输出并在需要时输出后,我似乎无法切换回STDIN父(shell)进程,这会导致下次我需要接受输入时出现段错误。

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

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;

以及处理完成后我从管道获取输出时的代码。

close(m_pipefd[1]);     
dup2(m_pipefd[0], STDIN_FILENO);
while(fgets(buffer, sizeof(buffer), stdin)) {
 buf = buffer;
 printf("%s\n", buf);
}
close(m_pipefd[0]);

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

谢谢,

布雷登

【问题讨论】:

    标签: c fork stdout stdin pipe


    【解决方案1】:

    通常不需要在你的父母中弄乱标准输入和标准输出。将 child 中的管道连接到 stdin 和 stdout 后,管道的另一端应该能够发送数据或从子级获取数据。

    只需从您父母的 m_pipefd[1] 中读取。

    【讨论】:

    • 谢谢,我不知道我在想什么。这解决了它。
    猜你喜欢
    • 1970-01-01
    • 2012-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-06
    • 1970-01-01
    • 2012-05-05
    • 2018-01-07
    相关资源
    最近更新 更多