Forking with Pipes

Posted by Luke on Stack Overflow See other posts from Stack Overflow or by Luke
Published on 2010-04-08T00:27:18Z Indexed on 2010/04/08 1:03 UTC
Read the original article Hit count: 441

Filed under:
|
|
|

Hello

I have tried to do fork() and piping in main and it works perfectly fine but when I try to implement it in a function for some reason I don't get any output, this is my code:

void cmd(int **pipefd,int count,int type, int last);    

int main(int argc, char *argv[]) {
int pipefd[3][2];
int i, total_cmds = 3,count = 0;
int in = 1;

for(i = 0; i < total_cmds;i++){
 pipe(pipefd[count++]);
 cmd(pipefd,count,i,0);    
}

 /*Last Command*/
 cmd(pipefd,count,i,1);    

exit(EXIT_SUCCESS);
}

void cmd(int **pipefd,int count,int type, int last){    
    int child_pid,i,i2;

     if ((child_pid = fork()) == 0) {

            if(count == 1){
               dup2(pipefd[count-1][1],1); /*first command*/
            }
            else if(last!=0){
               dup2(pipefd[count - 2][0],0); /*middle commands*/
               dup2(pipefd[count - 1][1],1);
            }
            else if(last == 1){
               dup2(pipefd[count - 1][0],0); /*last command*/
            }


            for(i = 0; i < count;i++){/*close pipes*/
            for(i2 = 0; i2 < 2;i2++){
               close(pipefd[i][i2]);
            }}



            if(type == 0){
                execlp("ls","ls","-al",NULL);
            }
            else if(type == 1){
                execlp("grep","grep",".bak",NULL);
            }
            else if(type==2){
                               execl("/usr/bin/wc","wc",NULL);
            }
            else if(type ==3){
                         execl("/usr/bin/wc","wc","-l",NULL);
           }
            perror("exec");
            exit(EXIT_FAILURE);
    }
    else if (child_pid < 0) {
            perror("fork");
            exit(EXIT_FAILURE);
    }
}

I checked the file descriptors and it is opening the right ones, not sure what the problem could be..

© Stack Overflow or respective owner

Related posts about unix-programming

Related posts about c