Note that there are some explanatory texts on larger screens.

plurals
  1. POConnecting n commands with pipes in a shell?
    primarykey
    data
    text
    <p>I am trying to implement a shell in C. I can execute simple commands just fine with a simple execvp() but one of the requirements is to manage commands like this: "ls -l | head | tail -4" with a 'for' loop and only one 'pipe()' statement redirecting stdin and stdout. Now after days I'm a bit lost.</p> <p>N = Number of simple commands (3 in the example: ls, head, tail) commands = a list of structs with the commands, like this:</p> <pre><code>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 </code></pre> <p>So, I made the for loop, and started to redirect stdin and stdout in order to connect all the commands with pipes, but...I'm just clueless why it doesn't work.</p> <pre><code>for (i=0; i &lt; n; i++){ pipe(pipe); if(fork()==0){ // CHILD close(pipe[0]); close(1); dup(pipe[1]); close(pipe[1]); execvp(commands[i].argv[0], &amp;commands[i].argv[0]); perror("ERROR: "); exit(-1); }else{ // FATHER close(pipe[1]); close(0); dup(pipe[0]); close(pipe[0]); } } </code></pre> <p>What I want to create is a 'line' of childed processes:</p> <blockquote> <p>[ls -l] ----pipe----> [head] ----pipe----> [tail -4]</p> </blockquote> <p>All this processes have a root (the process runing my shell) so, the first father is also a child of the shell process, I'm a bit exhausted already, can anyone help me here please?</p> <p>I'm not even sure if the childs should be the ones executing the commands.</p> <p>Thanks guys !!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload