1

古い宿題の質問を参照してください:/* 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 に組み込まれていますか? 私はこの概念を得ることができません。

4

2 に答える 2

1

あなたの質問は誤った前提に基づいています-execvどこからでも読んでおらず、読む必要もありません。への呼び出し全体で継承されるmoreから読み取ります。読み取り元の理由は、これがフィルターであるためです。ほとんどのフィルターと同様に、コマンド ラインで別の入力ソースが指定されていない場合、デフォルトで読み取り元になります。(そうしないとうまくいきません。)stdinexecvmorestdinstdin/usr/bin/ps -ef | /usr/bin/more

于 2012-07-07T08:42:27.950 に答える