I'm developing a simple shell in C but I'm experiencing some problems to execute pipe separated commands properly, such as: 'env | sort' and others which make usage of the pipe '|'.
As you may know, the pipe is the redirection of the stdout of the first command to the stdin of the second command. Therefore, in my program, when the user inputs commands in this format, my parser stores each command in a double linked list.
If when this insertion is performed the list is empty, then there is no need to make a call to pipe since we must have at least one element inserted as explained before. But if that is the case, this is, if I have at least an element already inserted, then I make a call to (suppose e.g. pipe(fd)); and then I store fd on the current element (which is the second command typed) and fd on the previous element of the list (first command typed). This means that the current element (second) will be reading the output of the previous element, which will be writing to fd.
Until now, no redirection is done but I've just set things to do that redirection properly.
Then, after this linked list is completed, I perform some checks to validate it so I can run all commands perfectly.
The process of running the command list is quite simple:
- Perform a fork;
- In the child code (pid == 0), I redirect its output to either fd or fd using the syscall dup2 which will be either dup2(fd, STDIN_FILENO) or dup2(fd, STDOUT_FILENO). Right after that I call close(fd) or close(fd) depending on what needs to be done by the child;
- Then I call execv with the command arguments to execute the typed command;
The problem I'm having is that I cannot see the output of whole chain of commands on
the shell. The last command typed does not perform any redirection of the stdout since it just receives different input since its stdin is redirected to its previous command. Everything is supposed to run correct.
What am I doing wrong?
Thanks in advance,