fork + pipe + dup2

Discussion in 'C' started by caio1985, Sep 6, 2010.

  1. caio1985

    caio1985 New Member

    Joined:
    Sep 6, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Hi,

    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[0] on the current element (which is the second command typed) and fd[1] 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[1].

    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:
    1. Perform a fork;
    2. In the child code (pid == 0), I redirect its output to either fd[0] or fd[1] using the syscall dup2 which will be either dup2(fd[0], STDIN_FILENO) or dup2(fd[1], STDOUT_FILENO). Right after that I call close(fd[0]) or close(fd[1]) depending on what needs to be done by the child;
    3. 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,
    Caio
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice