Two redirect in program

2019-07-29 04:29发布

问题:

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.

回答1:

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 :)



标签: c linux fork pipe