【问题标题】:Pipe and STDOUT管道和标准输出
【发布时间】:2015-10-31 09:47:41
【问题描述】:

我正在学习如何使用 fork 和管道,但我对这段代码有疑问:

int pid;
char *command_arg[] = {"date", NULL, NULL};

pid = fork();

if (pid == 0)
{
  execvp("date", command_arg);
}
else
{
  wait(NULL);
}

使用 execvp,我想运行命令“date”并将输出写入标准输出。我需要一个管道来将“日期”写入 STDOUT 吗?在这个例子中我该怎么做?

【问题讨论】:

  • 一定要试试这个吗?
  • 您知道stdin/stdout/stderr 的文件描述符是由孩子继承的吗?

标签: c pipe fork


【解决方案1】:

来自 fork() 手册页:

   *  The child inherits copies of the parent's set of open file  descrip‐
      tors.   Each  file  descriptor  in the child refers to the same open
      file description (see open(2)) as the corresponding file  descriptor
      in  the parent.  This means that the two descriptors share open file
      status flags, current file offset, and signal-driven I/O  attributes
      (see the description of F_SETOWN and F_SETSIG in fcntl(2)).

换句话说,您无需执行任何特殊操作即可将date 的输出发送到父级的标准输出。

【讨论】: