用C编码多管 [英] Coding multiple pipe in C

查看:138
本文介绍了用C编码多管的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现多管我的C shell中。

I'm trying to implement a multiple pipe for my shell in C.

我只有一个管道函数,管道| B,而不是| C |角

All I have is a pipe function that pipe a | b but not a | b | c.

int   c[2];
int   returnv;
pid_t id;

pipe(c);
pid = fork()) == 0
if (pid)
{
  dup2(c[1], 0);
  close(p[1]);
  close(p[1]);
  execvp(array(0), array);
}

if ((pid = fork()) == 0)
{
  dup2(p[0], 1);
  close(p(0));
  close(p[0]);
  returnv = execvp(array[0], array);
}

close(p[1]);
wait(NULL);
wait(NULL);
wait(NULL);
return returnv;

这是第二个版本:

And this is a second version:

int i = 0;

while (i < x)

{
 pipe(c);
 if ((pid = fork()) == 0)
 {
   dup2(t[i], 1);
   if (i < 2)
       dup2(p[0], 1);
   close(p[1]);
 r=  execvp(cmd[i][0], cmd[i]);
 }
     wait(NULL);
     close(p[0]);
     i += 1;
     t[i] = p[1];

我如何添加的小东西,这将使该code管理多个管好吗?
非常感谢事先!

How can I add the little something that will make this code manage multiple pipe please ? Thanks a lot in advance !

推荐答案

修改根据您的评论

according to your comment

要执行你需要存储你的所有命令的地方倍数管道。
这就是为什么我使用的结构的一个标签。

To perform multiples pipes you need to store all your commands somewhere. That's why I used a tab of structure.

检查新版本,也许更容易理解。

Check this new version maybe easier to understand

所以,首先你需要一个标签或东西存储所有的命令:

So first you need a tab or something to store all your commands:

int main()
{
  char *ls[] = {"ls", NULL};
  char *grep[] = {"grep", "pipe", NULL};
  char *wc[] = {"wc", NULL};
  char **cmd[] = {ls, grep, wc, NULL};

  loop_pipe(cmd);
  return (0);
}

谁就会通过Tab运行,并一切功能<​​/ P>

Then the function who will run through the tab and launch everything

void    loop_pipe(char ***cmd) 
{
  int   p[2];
  pid_t pid;
  int   fd_in = 0;

  while (*cmd != NULL)
    {
      pipe(p);
      if ((pid = fork()) == -1)
        {
          exit(EXIT_FAILURE);
        }
      else if (pid == 0)
        {
          dup2(fd_in, 0); //change the input according to the old one 
          if (*(cmd + 1) != NULL)
            dup2(p[1], 1);
          close(p[0]);
          execvp((*cmd)[0], *cmd);
          exit(EXIT_FAILURE);
        }
      else
        {
          wait(NULL);
          close(p[1]);
          fd_in = p[0]; //save the input for the next command
          cmd++;
        }
    }
}

这篇关于用C编码多管的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆