C, unix, pipes, fork, recursion

Hi, I will try to keep my post as compressed as my title was.
I am writing on pseudo code on a recursive function that I want to read from the one-above function-run and then give the result to the function-run down below until a stop is triggered. Example:

$ ls -la | grep x | sort

In my function what I want ls to run and send the result to the next function call.
What I've got so far:

main:
create a char **program_names and set int times_to_run to amount of names.
call rec(program_names, times_to_run)

rec(char** program_names, int times_to_run):
if times_to_run is 0 return, else do
int fd[2]
pipe(fd)
replace stdout with fd[1]
fork
parent:
    execl(*(program_names+times_to_run))
child:
    replace stdin with fd[0]
    //waitpid(getppid()) ?
    call rec(program_names, times_to_run-1)

Does this seem right? I'm having a hard time with recursion. :wall:
Cheers.

You aren't closing all the pipe ends you don't need. Each process gets an independent copy of the pipe ends. Any ends they don't need must be closed or they will gum up the works later -- your pipe won't ever close when the program using it closes if there are 3 extra writing ends hanging around which haven't.

Also, you need two pipes, because you can't add a pipe to a process later -- your grep has to have a pipe for input and a pipe for output right when you run it. And then you have to save the reading end of its writing pipe for the sort...

Also: Why bother with recursion, when a for-loop will do the same thing with less doublethink?