Implementation of ls | wc command

ls | wc command : Using ls|wc, we can count new lines, words and letters of all files of current directory. We can see from the following after execution of the code we get same results.

Prerequisites :ls command | wc command | piping in linux

Approach : First, we have to use pipe for inter process communication over an array where a[0] is used for reading and a[1] is used for writing. We can replicate the process using fork. In the parent process, standard output is closed so that output of ls command will go to a[0] and similarly standard input is closed in children process. Now, if we run the program output will be as same as command of linux ls|wc.

Below is the implementation of above approach :

[sourcecode language=”C”]
// C code to implement ls | wc command
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include<errno.h>
#include<sys/wait.h>
#include <unistd.h>
int main(){

// array of 2 size a[0] is for
// reading and a[1] is for
// writing over a pipe
int a[2];

// using pipe for inter
// process communication
pipe(a);

if(!fork())
{
// closing normal stdout
close(1);

// making stdout same as a[1]
dup(a[1]);

// closing reading part of pipe
// we don’t need of it at this time
close(a[0]);

// executing ls
execlp("ls","ls",NULL);
}
else
{
// closing normal stdin
close(0);

// making stdin same as a[0]
dup(a[0]);

// closing writing part in parent,
// we don’t need of it at this time
close(a[1]);

// executing wc
execlp("wc","wc",NULL);
}
}
[/sourcecode]



My Personal Notes arrow_drop_up

[ Intern at GeeksForGeeks ] I am a Computer Science and Engineering Undergraduate at MNNIT Allahabad I love to do competitive programming and software development I like to contribute open source projects I always believe in learning new technologies

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.