pipe 2 linux commands in C I am writing a simpel program that can basicly do the same as piping two linux commands can do. For example, ls -l | grep vars.sh, this can be done on the Linux console. I need to write a programm in C that can do the same. I think I got it working but I want to know if I am doing it rite and if there are some modifications I can do on my code.

Here is my code:

#include &lt;stdio.h&gt; // Voor verschillende I/O's, macro's, declaraties.
#include &lt;stdlib.h&gt; // Om de system call te activeren.
#include &lt;unistd.h&gt; // Laden van constanten en types.

int main()
{
    pid_t pid;
    int pipefd[2];
    pipe(pipefd);
    pid = fork();

    if(pid==-1){
        perror("pipe");
        exit(EXIT_FAILURE);
    }

    if(pid&gt;0){
        close(pipefd[0]);
        dup2(pipefd[1],1);
        execlp("ls","ls","-l",NULL);
    }
    else{
        close(pipefd[1]);
        dup2(pipefd[0],0);
        execlp("grep","grep",".bashrc",NULL);
        exit(EXIT_FAILURE);
    }
}


Any feedback,rewrites or modifications are welcome.
The only other way that I could see this can be done in POSIX would be to use popen() rather than using raw pipes.  It also returns a stream pointer that can be used with the C standard I/O functions like fprintf(), fgets(), etc. to read and/or write to the process on the other-side of the pipe created by popen().  According to the POSIX specification, with popen(), 


  The environment of the executed
  command shall be as if a child process
  were created within the popen() call
  using the fork() function, and the
  child invoked the sh utility using the
  call:
  
  execl(shell path, "sh", "-c", command,
  (char *)0);
  
  where shell path is an unspecified
  pathname for the sh utility.


So it's basically an easier, more straight-forward way to work with pipes rather than having to fork child processes yourself and close the un-used portions of the pipe so that you don't end up with accidental blocking reads or lost writes because there are still active file-descriptors on each end of the pipe that you've accidentally forgotten to close in either the parent or child process.

With your example, using popen() would look like the following:

#include &lt;stdio.h&gt;
#define BUFFERSIZE 128

FILE *ls_proc, *grep_proc;
ls_proc = popen("ls -l", "r");
grep_proc = popen("grep .bashrc", "w");

char buffer[BUFFERSIZE];

//read from one child process and write to the other
while (fgets(buffer, BUFFERSIZE, ls_proc) != NULL)
    fprintf(grep_proc, "%s", buffer);

pclose(ls_proc);
pclose(grep_proc);