Tingrammer
Tingrammer

Reputation: 251

Pipe implementation in Linux using c

I am trying to implement following command,

ls | grep "SOMETHING"

in c programming language. Can anybody please help me with this.

I want to fork a child , where i will run ls command using execlp. In the parent i get the output of the child and grep (once again using execlp).

Is it not possible?

Upvotes: 1

Views: 14435

Answers (2)

Tingrammer
Tingrammer

Reputation: 251

I finally found the code for it.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
int pfds[2];
pipe(pfds);
if (!fork()) {
    close(1);       /* close normal stdout */
    dup(pfds[1]);   /* make stdout same as pfds[1] */
    close(pfds[0]); /* we don't need this */
    execlp("ls", "ls", NULL);
} else {
    close(0);       /* close normal stdin */
    dup(pfds[0]);   /* make stdin same as pfds[0] */
    close(pfds[1]); /* we don't need this */
    execlp("grep", "SOMETHING", NULL);
}
return 0;
}

Upvotes: 8

Mr. C
Mr. C

Reputation: 568

The pipe is just read from one stdout and write to the other stdin.
Do you want to implement a shell interpreter with pipe feature?
First, you need a shell parser to parse the commond.
Then, you would have a pipe line feature.
...

Upvotes: 3

Related Questions