I have to build a program that simulates the shell pipe |.
For an instance, if the user calls my program like this:
% myprogram ls -1 :: sort :: more
I have to return the same results that the shell would return to ls -1 | sort |more .
However, everything I try just fails miserably.
I have tried something like this, using two pipes:

Code:
while(loop through the arguments)
{
    /* suppose that at this point of the code we know the current program to run, with all it's arguments */    
    fork();
    if(child is running)
    {
        if(this is not the first program)
            change child's stdin to currentpipe's read side
        if(this is not the last program)
            change child's stdout to otherpipe's write side
        close all sides of all pipes
        change current pipe to the other pipe
        run exec
    }
    else /*we are on the parent process */
        wait for the child process
    return 0;
}
When I execute it with only one program on the arguments, the results are printed ok, but the program doesn't exit. With more than one argument, nothing happens and the program doesn't exit.
If I remove the wait for the child, the same scenario happens, with the difference that the program exits.
What am I doing wrong?