GFXGunblade
GFXGunblade

Reputation: 97

Iterative piping implementation for linux in c

I know this question gets asked a lot but I am still really confused as to how to go about fixing my problem. I have attempted to write code that handles command line input for the possibility of several pipes. However, I am unsuccessful and my code, although executing does not work correctly. The bug is once I've forked the children, I cannot get to the next command that the pipe goes to after the very first command executes. How do I move to the next command in the pipe without grabbing the wrong file descriptors? Here is a chunk of code;

      a = 0;
      while (a < cmdnum)
      {
      pid[a] = fork();
      if( pid[a] == 0)
      {
      if( a == 0)
        {

          close(1);
          dup(p1_to_pn[a][1]);
          for( k = 0; k < nump; k++)
            {
              close(p1_to_pn[k][0]);
              close(p1_to_pn[k][1]);
            }  

          args = tokenize(cmd[a]);
          execv(args[0], args);
        }
      else if ( a == (cmdnum-1))
        {

          close(0);
          dup(p1_to_pn[a][0]);
          for( k = 0; k < nump; k++)
            {
              close(p1_to_pn[k][0]);
              close(p1_to_pn[k][1]);
            }
          args = tokenize(cmd[a]);

          i = execv(args[0], args);
        }
      else
        {

          close(0);
          dup(p1_to_pn[a][0]);
          close(1);
          dup(p1_to_pn[a][1]);
          for( k = 0; k < nump; k ++)
            {
              close(p1_to_pn[k][0]);
              close(p1_to_pn[k][1]);
           }
          args = tokenize(cmd[a]);

          execv(args[0], args);
        }
    }
  a++;
}

Upvotes: 0

Views: 459

Answers (1)

Charlie Martin
Charlie Martin

Reputation: 112386

Your mistake is thinking you need to move to the "next" command. Start them all.

Here's the basic idea, for a pipeline like A | B | C

The parent process reads the command line. For each new command, it is going to fork a new process, and eventually exec it. The parent process already has fd 0,1,2 open (STDIN, STDOUT, and STDERR.) When you hit the pipe, use the pipe(2) and dup(2) system calls to make a new fd; fork the next process.

All the fd manipulation happens in the parent process.

Upvotes: 1

Related Questions