I want to implement a linux shell interpreter which takes multiple piped commands such as "ls| grep c| sort | less" as input and gives the output on the command line as well as saves the output in a file in c, using pipes and tees only. I modified the code given in the answer in this link: Connecting n commands with pipes in a shell?
In my code, pipestr is the array of piped commands and parsed contains the space seperated arguments of a command i.e for the above example pipestr will have ["ls","grep c","sort","less"] and parsed for each of them would be : parsed[0]=["ls"], parsed[1]=["grep","c"] and so on.
I am getting the output on the command line, however nothing is being written to the file using the tee function? Kindly help.
int pipeex(int in,int out, char ** parsed)
{
pid_t p;
p=fork();
if(p==0)
{
if(in!=0)
{
dup2(in,0);
close(in);
}
if(out!=1)
{
dup2(out,1);
close(out);
}
if(execvp(parsed[0],parsed)<0)
{
printf("Command not executed\n");
status=-1;
}
}
else
{
wait(NULL);
}
}
In the main function:
for(i=0;pipedstr[i]!=NULL;i++)
{
parseSpace(pipedstr[i],parsed);
pid_t p;
if(i!=noofpipe-1)
{
pipe(fd);
pipeex(in,fd[1],parsed);
close(fd[1]);
in=fd[0];
}
else
{
pid_t p1;
p1=fork();
if(p1==0)
{
close(fd[1]);
in=fd[0];
if(in !=0)
dup2(in,0);
fo = open("lf.txt", O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU);
statu = tee(STDOUT_FILENO,fo,INT_MAX, SPLICE_F_NONBLOCK);
close(fo);
if(execvp(parsed[0],parsed)<0)
{
printf("Command not executed\n");
status=-1;
}
}
else
{
wait(NULL);
}
}
}