程序中的两个重定向 [英] Two redirect in program

查看:149
本文介绍了程序中的两个重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试用C语言编写命令解释器.我必须创建dwo和三个重定向(例如ls | grep ^d | wc -lls -ps | grep / | pr -3 | more)

我有操作一个重定向的代码

    if(k==1)
{
  int pfds[2];
  pipe(pfds);
  child_pid = fork();
  if(child_pid==0)
  {       
    close(1);       
        dup(pfds[1]);   
        close(pfds[0]); 
        execlp(arg1[0], *arg1, NULL);
  }
  else 
  {
        close(0);      
        dup(pfds[0]);
        close(pfds[1]); 
        execlp(arg2[0], *arg2, NULL);
  }     
}

我的问题是如何使用pipefork进行两次和三次重定向?

我尝试仅使用一个管道来执行此操作,但这不起作用.

解决方案

您将不得不创建与转移"一样多的pipe变量. 然后创建命令列表.

如果您希望父进程离开,则可以为每个命令派生一个进程.否则少一遍.

对于第一个命令,dup或"dup2"仅用于STDOUT.

,并且对于最后一个命令dup或'dup2'仅适用于STDIN.

对于其余部分,对于STDIN和STDOUT都是dup或'dup2`.

您可以使用从第二倒数第二个倒数第二个for循环进行此操作.

例如: 外壳$> cat file.txt | grep'pattern1 | pattern2'| grep'pattern1'| wc -l <​​/p>

我假设您没有将父进程用于exec 因此,您将创建命令的列表/数组/向量.列表将具有所有4个命令. 在父进程本身中为每个命令创建4个管道.

运行一个循环进行4次迭代,每个循环用于一条命令.

  • 分叉一个过程.
  • 如果是父进程,请继续.
  • 其他(孩子)
    • 仅对第一个命令(cat)使用dup/dup2 STDOUT.
    • dup/dup2仅STDIN用于最后一个命令(wc -l).
    • 否则要分别对STDIN和STDOUT进行dup/dup2.
    • 然后运行exec.

干杯:)

I try write a command interpreter in C. I must create dwo and three redirects (e.g. ls | grep ^d | wc -l and ls -ps | grep / | pr -3 | more)

I have code to operate one redirects

    if(k==1)
{
  int pfds[2];
  pipe(pfds);
  child_pid = fork();
  if(child_pid==0)
  {       
    close(1);       
        dup(pfds[1]);   
        close(pfds[0]); 
        execlp(arg1[0], *arg1, NULL);
  }
  else 
  {
        close(0);      
        dup(pfds[0]);
        close(pfds[1]); 
        execlp(arg2[0], *arg2, NULL);
  }     
}

My question is how make two and three redirects using pipe and fork?

I try do this using only one pipe but this in not work.

解决方案

you will have to create as many pipe variables as there are "diversion". then create a list of commands.

if you want parent process leave,you would fork a process for each command. otherwise one less.

for the very first command, dup or 'dup2` only for STDOUT.

and for the very last command dup or 'dup2` only for STDIN.

for the rest, dup or 'dup2` for STDIN and STDOUT both.

you can do this with a for loop from 2nd to second-last.

For Example: shell $> cat file.txt | grep 'pattern1|pattern2' | grep 'pattern1' | wc -l

I am assuming you are not using parent process for exec So, you would create a list/array/vector of commands. list would have all 4 commands. create 4 pipes for each commands in parent process itself.

run a loop for 4 iteration, each for a command.

  • fork one process.
  • if parent process, continue.
  • else(child)
    • dup/dup2 only STDOUT for first command(cat).
    • dup/dup2 only STDIN for last command(wc -l).
    • dup/dup2 both STDIN and STDOUT otherwise.
    • then run exec.

CHEERS :)

这篇关于程序中的两个重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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