Home > OS >  piping for a simple shell in c
piping for a simple shell in c

Time:10-04

I'm trying to implement piping in a simple shell program that I'm writing in C.

But for some reason, I'm not getting output when I try to run ls | wc -l.

I'm really not sure why this is happening since I'm basically putting the child process's output to pipe[1] which does the command before pipe indicator and I'm putting parent's input to pipe[0] which does the command after pipe indicator and it should be printing to the terminal since the output of parent's never been changed, my approach right now is if piping is flagged the call fork in child and do the piping.

code below

int pipe1[2];
int pipepid;
int piping; /*flag for piping*/
int pipeposition;/*index of pipe indicator*/
//* code... */
            if(pipe(pipe1)!= 0){
                perror("pipe");
                exit(1);
            };
/* split commands to before pipe indicator and after */
            for(int p = 0;p<pipeposition;p  ){
                argsbefore[p]=args[p];
            }
            /* after */
            int e=0;
            for(int h = pipeposition 1; h<cnt;h  ){
                argsafter[e]=args[h];
                e  ;
            }
/* code ... */
            if(piping){
                pipepid = fork();
                if(pid == 0){
                    /* do child */
                    if(dup2(pipe1[1],1)==-1){
                        perror("dup2 child");
                        exit(1);
                    }
                    close(pipe1[1]);
                    if (execvp(argsbefore[0], argsbefore) < 0) { 
                        printf("exec failed\n");
                        exit(1); 
                    }
                    exit(0);
                }/* else if error */
                else if(pid == -1){
                    printf("ERROR: fork failed\n");
                    exit(1);
                }/* parent */
                else{
                    if(dup2(pipe1[0],0)==-1){
                        perror("dup2 parent");
                        exit(1);
                    }
                    close(pipe1[0]);
                    if (execvp(argsafter[0], argsafter) < 0) { 
                        printf("exec failed\n");
                        exit(1);
                    } 
                }

            }

CodePudding user response:

you seem to be doing that on a unix-like system. If you're lucky, your system might have a tool that reports every system call your program perform (strace -f my_program my_ar gu_ments would do that on Linux).

That would give you a list of what process did what and when, and whether there have been error code for some operations. That usually helps a lot with these multi-process setups.

CodePudding user response:

It turns out I didn't close all the pipes so the second command wasn't able to finish, after putting close for both ends in the main parent process it was fixed

  • Related