Implementation of ls | wc command
Last Updated :
30 Apr, 2018
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 :
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include<errno.h>
#include<sys/wait.h>
#include <unistd.h>
int main(){
int a[2];
pipe(a);
if (!fork())
{
close(1);
dup(a[1]);
close(a[0]);
execlp( "ls" , "ls" ,NULL);
}
else
{
close(0);
dup(a[0]);
close(a[1]);
execlp( "wc" , "wc" ,NULL);
}
}
|
Share your thoughts in the comments
Please Login to comment...