For an assignment we need to implement a basic shell with re-directions and pipes. My code for the pipe exits the program and does not ask for the user input again. The pipe is executed in a function, so basically the control is not returned to main. How do I make it do so ? Here is my code :
void execute_pipe(char **argv,char **args)
{
int pfds[2];
pid_t pid;
int status;
pipe(pfds);
if ((pid = fork()) < 0) {
printf("*** ERROR: forking child process failed\n");
exit(1);
}
printf("here");
if (pid==0) {
close(1);
dup(pfds[1]);
close(pfds[0]);
if(execvp(argv[0],argv)<0){
printf("**error in exec");
}
}
else {
while (wait(&status) != pid) ;
close(0);
dup(pfds[0]);
close(pfds[1]);
if(execvp(args[0],args)<0){
printf("**error in exec");
}
}
}
If you
dup()ordup2()a pipe to standard input or standard output, you should close both of the file descriptors for the pipe before usingexecvp()or one of its relatives. Add:to the child code.
The child process has to die before you run the parent process (because you
wait()in a loop). Note that you should check thatwait()does not return an error such as ECHILD; if it does, you won’t get beyond the loop. Again, you should be closing both the pipe file descriptors.Note that if the child generates more data than will fit in the pipe, the child will be blocked writing to the pipe, while the parent is blocked waiting for the child to die — deadlock.
You can’t make that code return to
main()unless either the child or the parent fails toexecvp()the command it is given. You would need an extrafork()in there, most probably.And the waiting would normally be done by the parent process, not by one of the two children.