【问题标题】:How execv gets the output from pipe?execv 如何从管道获取输出?
【发布时间】:2012-07-07 08:29:59
【问题描述】:

参考旧作业问题:/* implementing "/usr/bin/ps -ef | /usr/bin/more" */ 使用管道。

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main()
{
  int fds[2];
  int child[2];
  char *argv[3];
  pipe(fds);
  if (fork()== 0) {
    close(fds[1]);
    close(STDIN_FILENO); dup(fds[0]); /* redirect standard input to fds[1] */
    argv[0] = "/bin/more";
    argv[1] = NULL;           /* check how the argv array is set */
    execv(argv[0], argv);// here how execv reads from stdin ??
    exit(0);


  }
  if (fork() == 0) {
    close(fds[0]);
    close(STDOUT_FILENO); dup(fds[1]);  /* redirect standard output to fds[0] */
    argv[0] = "/bin/ps";
    argv[1] = "-e"; argv[2] = NULL;
    execv(argv[0], argv);
    exit(0);

  }

  close(fds[1]);
  wait(&child[0]);
  wait(&child[0]);  
} 

将 fd 重定向到标准输出后,execv 是如何读取它的。在执行命令之前它是否内置在 execv 中,它会从标准输入中读取?我无法理解这个概念。

【问题讨论】:

    标签: c operating-system execv


    【解决方案1】:

    您的问题基于一个错误的前提——execv 不会从任何地方读取,也不需要读取。从stdin 中读取的是more,它在对execv 的调用中继承。 more 从 stdin 读取的原因是因为它是一个过滤器,并且与大多数过滤器一样,如果未在命令行上指定另一个输入源,它默认从 stdin 读取。 (否则,/usr/bin/ps -ef | /usr/bin/more 将不起作用。)

    【讨论】:

    • 谢谢先生!这是正确的。我想错了方向。现在我知道了。这就是为什么像“ps | ls”这样的命令将只打印 ls 的输出。
    【解决方案2】:

    在您的第二次fork 电话中,我会更改以下代码:

      if (fork() == 0) {
        close(fds[0]);
    

    到这里:

      close(fds[0]);
      if (fork() == 0) {
    

    ps 调用的 argv[1] 应为 -ef。

    所有程序都将从stdin 读取以获取终端输入并写入stdout 以将数据传送到终端,如果它们不做任何事情来更改这些流的默认设置。代码所做的是将stdin 修改为more 并将stdout 修改为ps。 more 的 stdout 与当前进程(父进程)相同。因此,您的程序将ps 终端输出数据重定向为more 的终端输入。

    pipe 调用返回两个单向相互连接的文件描述符。当ps 写入它的stdout 时,它会转到dupd fds[1]。当more 读取它的stdin 时,它是dupd fds[0]。所以,more 获取了ps 的输出。

    【讨论】:

      猜你喜欢
      • 2017-10-19
      • 1970-01-01
      • 2021-10-28
      • 2021-09-16
      • 1970-01-01
      • 2013-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多