管道和标准输出

Pipe and STDOUT

我正在学习如何使用 fork 和 pipes,但我在使用这段代码时遇到了问题:

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

pid = fork();

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

我想使用 execvp 运行 命令 "date" 并将输出写入标准输出。我在这里需要一个用于将 "date" 写入 STDOUT 的管道吗?在这个例子中我该怎么做?

来自 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 的输出输出到父级的标准输出。