Shell and job with multiple commands

95 views Asked by At

I'm currently working on a small shell and I'm trying to implement the execution of a job composed of multiple commands (such as "ls | sort"). I'm facing a problem when it comes to redirection since the sort program seems to encounter a "Bad file descriptor". Here's the code:

For the first command:

 if (pipe(job->tubes[num_comm]) == -1)
                    {
                            perror("Erreur création tube");
                            exit(errno);
                    }
                    pid_t pid = fork();
                    if(pid==0) {
                            sig->sa_handler=SIG_DFL;
                            sigaction(SIGINT, sig, NULL);
                            close(job->tubes[num_comm][0]);
                            dup2(job->tubes[num_comm][1], 1);
                            close(job->tubes[num_comm][1]);
                            execvp(ligne_analysee->commandes[num_comm][0], ligne_analysee->commandes[num_comm]);
                    }
                    job->pids[num_comm]=pid;
                    close(job->tubes[num_comm][0]);

For the last command:

                    pid_t pid = fork();
                    if(pid==0) {
                            dup2(job->tubes[num_comm-1][1], 0);
                            close(job->tubes[num_comm-1][1]);
                            sig->sa_handler=SIG_DFL;
                            sigaction(SIGINT, sig, NULL);
                            execvp(ligne_analysee->commandes[num_comm][0], ligne_analysee->commandes[num_comm]);
                    }
                    job->pids[num_comm]=pid;
                    close(job->tubes[num_comm][1]);

Thanks for your help!

1

There are 1 answers

0
aslad On

I had misunderstood the way pipes work, the write end is to be modified by the child but not the parent, the read end should be directly closed on the child. The parent should leave the read end open for the next child to read from it (the second command in our case)... Thanks, problem solved!