在shell中使用管道连接n个命令?

33

我正在尝试用C语言实现一个shell。使用简单的execvp()可以正常执行简单命令,但其中一个要求是使用'for'循环和只有一个'pipe()'语句来处理像这样的命令:"ls -l | head | tail -4"。经过数天的尝试,我有些迷失了。

N = 简单命令的数量(例如此示例中为3个:ls、head、tail) commands = 命令列表的结构体,类似于这个:

commands[0].argv[0]: ls
commands[0].argv[1]: -l
commands[1].argv[0]: head
commands[2].argv[0]: tail
commands[2].argv[1]: -4

所以,我已经写了for循环,并开始重定向标准输入输出,以便使用管道连接所有的命令,但是......我不知道为什么它不起作用。

for (i=0; i < n; i++){

pipe(pipe);
if(fork()==0){  // CHILD

    close(pipe[0]);
    close(1);
    dup(pipe[1]);
    close(pipe[1]);

    execvp(commands[i].argv[0], &commands[i].argv[0]);
    perror("ERROR: ");
    exit(-1);

}else{      // FATHER

    close(pipe[1]);
    close(0);
    dup(pipe[0]);
    close(pipe[0]);

}
}
我想要创建的是一个“子进程链”,如下所示:

[ls -l] ----管道----> [head] ----管道----> [tail -4]

所有这些进程都有一个根进程(即运行我的shell的进程),因此,第一个父进程也是shell进程的子进程。我已经感到有点疲惫了,请问有人可以帮助我吗?
我甚至不确定子进程是否应该执行命令。
谢谢大家!!

这是作业吗?如果不是,只需使用适当的参数运行 /bin/sh。为什么要重复造轮子呢? - Ed Heal
这只是三页自愿练习中的一个要求。虽然不完全是作业,但我想知道如何做到这一点,或者至少得到一些线索。 - vicpermir
这里在S.O.上有许多优秀的帖子,涵盖了你需要掌握这个主题的背景材料。祝你好运。 - shellter
@user1031296,你能否发布完整的代码? - ss321c
2个回答

68

这里没有什么复杂的东西,只需要记住最后一个命令应该输出到原始进程的文件描述符1,第一个应该从原始进程的文件描述符0读取。您只需按顺序生成进程,并携带前一个pipe调用的输入端。

因此,这是类型:

#include <unistd.h>

struct command
{
  const char **argv;
};

编写一个帮助函数,具有简单明确的语义:

int
spawn_proc (int in, int out, struct command *cmd)
{
  pid_t pid;

  if ((pid = fork ()) == 0)
    {
      if (in != 0)
        {
          dup2 (in, 0);
          close (in);
        }

      if (out != 1)
        {
          dup2 (out, 1);
          close (out);
        }

      return execvp (cmd->argv [0], (char * const *)cmd->argv);
    }

  return pid;
}

这里是主分支程序:

int
fork_pipes (int n, struct command *cmd)
{
  int i;
  pid_t pid;
  int in, fd [2];

  /* The first process should get its input from the original file descriptor 0.  */
  in = 0;

  /* Note the loop bound, we spawn here all, but the last stage of the pipeline.  */
  for (i = 0; i < n - 1; ++i)
    {
      pipe (fd);

      /* f [1] is the write end of the pipe, we carry `in` from the prev iteration.  */
      spawn_proc (in, fd [1], cmd + i);

      /* No need for the write end of the pipe, the child will write here.  */
      close (fd [1]);

      /* Keep the read end of the pipe, the next child will read from there.  */
      in = fd [0];
    }

  /* Last stage of the pipeline - set stdin be the read end of the previous pipe
     and output to the original file descriptor 1. */  
  if (in != 0)
    dup2 (in, 0);

  /* Execute the last stage with the current process. */
  return execvp (cmd [i].argv [0], (char * const *)cmd [i].argv);
}

还有一个小测试:

int
main ()
{
  const char *ls[] = { "ls", "-l", 0 };
  const char *awk[] = { "awk", "{print $1}", 0 };
  const char *sort[] = { "sort", 0 };
  const char *uniq[] = { "uniq", 0 };

  struct command cmd [] = { {ls}, {awk}, {sort}, {uniq} };

  return fork_pipes (4, cmd);
}

看起来可行。 :)


2
在子进程中未关闭未使用的fd[0];除了最后一个管道,父进程应该关闭两个管道的端口。 - jfs
@user1031296:要重定向到文件,请在最后一个阶段添加以下内容:if (file_fd != 1) { dup2(file_fd, 1); close(file_fd); } - jfs
那么你根本不需要使用wait()或waitpid()吗? - kanitw
@chill:我根据你的回答创建了一个代码示例,考虑了我上面的评论:pipeline-three-processes.c - jfs
4
父进程应该等待子进程输出,对吗? - bawejakunal
显示剩余6条评论

4

首先,您过早地关闭了管道。仅关闭当前进程中不需要的末尾,并记得在子进程中关闭stdin / stdout。

其次,您需要记住上一个命令的fd。因此,对于两个进程,操作如下:

int pipe[2];
pipe(pipe);
if ( fork() == 0 ) {
     /* Redirect output of process into pipe */
     close(stdout);
     close(pipe[0]);
     dup2( pipe[1], stdout );
     execvp(commands[0].argv[0], &commands[0].argv[0]);
} 
if ( fork() == 0 ) {
     /* Redirect input of process out of pipe */
     close(stdin);
     close(pipe[1]);
     dup2( pipe[0], stdin );
     execvp(commands[1].argv[0], &commands[1].argv[0]);
}
/* Main process */
close( pipe[0] );
close( pipe[1] );
waitpid();

现在你的任务是为此添加错误处理并生成n-1个管道以启动n个进程。第一个fork()块中的代码需要针对1..n-1进程的适当管道运行,而第二个fork()块中的代码需要针对2..n进程运行。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接