简体   繁体   中英

Shell and job with multiple commands

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!

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM