管道和STDOUT

时间:2015-10-31 09:47:41

标签: c pipe fork

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

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

pid = fork();

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

使用execvp我想运行命令" date"并将输出写入stdout。我需要一个用于写作的管道" date"到STDOUT?我在这个例子中如何做到这一点?

1 个答案:

答案 0 :(得分:2)

从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输出到父母的标准输出。