【问题标题】:Connecting n commands with pipes in a shell?在shell中用管道连接n个命令?
【发布时间】:2011-12-26 08:16:01
【问题描述】:

我正在尝试在 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 循环,并开始重定向标准输入和标准输出,以便将所有命令与管道连接,但是......我只是不知道为什么它不起作用。

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进程的一个孩子,我已经有点累了,有人可以帮我吗?

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

谢谢大家!!

【问题讨论】:

  • 这是作业吗?如果不是 - 只需使用适当的参数运行 /bin/sh。为什么要重新发明轮子?
  • 这只是 3 页长的自愿实践的要求之一。不完全是家庭作业,但我想知道如何做,或者至少得到一些线索。
  • 在 S.O. 上有很多好帖子。涵盖了您掌握该主题所需的背景材料。祝你好运。
  • @user1031296 你能把完整的代码贴出来

标签: c shell posix pipe


【解决方案1】:

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

似乎可以工作。 :)

【讨论】:

  • 非常有趣,似乎有效。是时候稍微弄乱一下代码了:P
  • 这工作得很好,但在一种情况下,我尝试重定向管道链的输出会引发一个奇怪的错误。我的意思是像“ls -l | head > file”。
  • @user1031296,为我工作, const char *ls[] = { "ls", "-l", 0 }; const char *head[] = { "head", 0 };结构命令 cmd [] = { {ls}, {head} }; return fork_pipes(2, cmd);
  • 未使用的fd[0] 未在子进程中关闭;除最后一个管道外,两个管道末端都应在父级中关闭。
  • 父母应该等待孩子输出吧?
【解决方案2】:

首先,您过早地关闭了管道。只关闭当前进程中不需要的那一端,记得在child中关闭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 运行。

【讨论】:

    猜你喜欢
    • 2019-07-28
    • 2018-10-23
    • 1970-01-01
    • 1970-01-01
    • 2017-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多