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

标签 c shell posix pipe

我正在尝试在 C 中实现一个 shell。我可以使用简单的 execvp() 执行简单的命令,但其中一个要求是管理这样的命令:“ls -l | head | tail -4”一个“for”循环和一个重定向标准输入和标准输出的“pipe()”语句。几天后,我有点迷路了。

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 循环,并开始重定向 stdin 和 stdout 以便将所有命令与管道连接起来,但是......我只是不知道为什么它不起作用。

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] ----pipe----> [head] ----pipe----> [tail -4]

所有这些进程都有一个根(运行我的 shell 的进程)所以,第一个父亲也是 shell 进程的 child ,我已经有点累了,有人可以帮我吗?

我什至不确定 child 是否应该是执行命令的人。

谢谢大家!!

最佳答案

这里没有什么复杂的,只要记住最后一个命令应该输出到原始进程的文件描述符 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;
}

这是主要的 fork 例程:

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);
}

似乎有效。 :)

关于在 shell 中用管道连接 n 个命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8082932/

相关文章:

c - 在 SIGTRAP 上是否有任何获取指令指针的不可知方法?

c - C中for语句中变量声明的区别

合作工具组 : coding in C

regex - 解析 git status 日志,如果修改的文件来自给定目录则退出

python - 管道连接导致从 python 调用的 shell 脚本中的管道损坏

c - 读写共享内存

c - GNU C 使用管道的多进程处理

c - Make 仅在第二次运行时使用 VPATH?

c - 通过优化使用C,gcc,C99和Macros改善微 Controller 的简约OOP

Linux:将字数 append 到文件的每一行