Hi,
I am trying to emulate the '|' functionality through pipe function call. I am passing the o/p of exec in parent as input to the exec in child. The buf is readin the o/p but the exec in child is not working. Can somebody checkout the code and point where am i going wrong or missing something.
ls | wc -l
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/wait.h>
int main(){
int piped[2];//pipe descriptors
char buf[16 * 1024];
pid_t child;
if(pipe(piped)<0){
fprintf(stderr,"pipe creation failed \n");
exit(-1);
}
if((child = fork()) < 0){
fprintf(stderr,"process creation failed \n");
exit(-1);
}
else if(child == 0){
close(piped[1]);//close the write end of child
close(0);//close stdin
if((dup2(piped[0],0)) < 0){//duplicate read end with stdin;
fprintf(stderr,"duplication of pipe desc failed \n");
exit(-1);
}
int linesrd = read(piped[0],buf,sizeof(buf));
printf("The noof bytes read are %d \n",linesrd);
if(linesrd < 0)
fprintf(stderr,"Read error \n");
buf[strlen(buf)-1] = '\0';
char *buf1 = buf;
execlp("wc","wc","-l",buf1,NULL);
//exit(1);
}
else{
close(piped[0]);//close read end of pipe
close(1);//close stdout
if(dup2(piped[1],1) < 0){//duplicate write end with stdout
fprintf(stderr," duplication error \n");
exit(-1);
}
int w=execlp("ls","ls",NULL);
close(piped[1]);
if(w<0){
fprintf(stderr,"Something went wrong \n");
exit(-1);
}
wait(NULL);
}
return(0);
}
output of code:
ameya@ameya-Dell-System-Inspiron-N4110:~/os_concepts$ The noof bytes read are 247
wc: a.out
basic_shell
Chapter6.pdf
communication
eof.c
fork-wait-exec
l5.pdf
OS_scheduling
pipe
pipe1.c
Regards,
Ameya