0

我需要分叉一个进程,在缓冲区中重定向输出(stdout 和 stderr)。我的代码似乎适用于大多数二进制文件,但不是全部。例如,我可以使用 ls -R /proc/ 之类的很长的“ls”来运行我的代码,并且它运行良好。当我运行 mke2fs 进程时,我的代码不再工作。

如果我在 fork 中运行 mke2fs 并等待它,它工作得很好。现在,如果我添加重定向的东西,我的程序永远不会完成运行。

我写了一点 main 来测试这个具体的麻烦:

#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main ()
{
  pid_t pid;
  int status = -42;
  int pipefd_out[2];
  int pipefd_err[2];
  char buf_stderr[1024];
  char buf_stdout[1024];
  int count;
  int ret;

  pipe(pipefd_out);
  pipe(pipefd_err);

  memset (buf_stdout, 0, 1024);
  memset (buf_stderr, 0, 1024);

  pid = fork ();

  if (pid == -1)
  {
    fprintf (stderr, "Error when forking process : /usr/sbin/mke2fs\n");
    return 1;
  }

  if (pid == 0)
  {
    close(pipefd_out[0]);
    close(pipefd_err[0]);

    dup2(pipefd_out[1], 1);
    dup2(pipefd_err[1], 2);

    close(pipefd_out[1]);
    close(pipefd_err[1]);

    char **args;

    args = malloc (sizeof (1024));
    args[0] = strdup("/usr/sbin/mke2fs");
    args[1] = strdup("/dev/sda4");
    args[2] = strdup("-t");
    args[3] = strdup("ext4");
    args[4] = NULL;

    execvp ("/usr/sbin/mke2fs", args);

    /*
    args = malloc (sizeof (1024));
    args[0] = strdup("/bin/ls");
    args[1] = strdup("-R");
    args[2] = strdup("/proc/irq");
    args[3] = NULL;

    execvp ("/bin/ls", args);
    */
    perror ("execv");
    fprintf (stderr, "Error when execvp process /usr/sbin/mke2fs\n");
    return 1;
  }
  close(pipefd_out[1]);
  close(pipefd_err[1]);

  if (waitpid(pid, &status, 0) == -1)
  {
    fprintf (stderr, "Error when waiting pid : %d\n", pid);
    return 1;
  }

  do
  {
    count = read(pipefd_out[0], buf_stdout, sizeof(buf_stdout));
  }
  while (count != 0);
  do
  {
    count = read(pipefd_err[0], buf_stderr, sizeof(buf_stderr));
  }
  while (count != 0);

  ret = WEXITSTATUS(status);

  FILE* file = NULL;
  file = fopen("/root/TUTU", "w");

  if (file != NULL)
  {
    fwrite(buf_stdout, 1, sizeof(buf_stdout), file);
    fwrite(buf_stderr, 1, sizeof(buf_stdout), file);
    fclose(file);
  }

  return 0;
}

如果我运行 ps,我可以看到我的子进程正在运行:

# ps | grep sda4
  936 root      2696 S    {mke2fs}  /dev/sda4 -t ext4

我无法理解为什么我会出现这种奇怪的行为。不确定它是否相关,但 mke2fs 的输出不是经典的。该过程似乎在计算期间更新输出,而不是打印输出并向前推进提示。它是一种进度条。不确定我的解释是否真的很清楚。

谢谢,伊娃。

4

1 回答 1

2

waitpid在从管道读取它的 stdout/stderr 之前,你不能等待程序完成(你用 做什么)。当程序写入管道并且它已满时,它将休眠,直到您从管道中读取以在其中腾出空间。因此,程序会一直等到管道中有更多空间才能继续并退出,而您正在等待程序退出,然后再从管道中读取以腾出空间。

在这种情况下,最简单的解决方案是移动waitpid直到完成管道读取。应该没问题,因为您执行的程序将在退出时关闭管道。

于 2013-12-17T13:21:38.247 回答