After incorporating Ben Voigt's answer into the code, it appears to work
Original question:
I'm trying to use dup2 to:
- pass the output of "ls -al" as input to "grep foo",
- whose output becomes input for "grep bar",
- which finally outputs to stdout.
The final output is (blank), the file "in" is (blank) & the file "out" has the output of "ls -al".
Any ideas what could be happening?
int main()
{
pid_t pid;
int i;
int inFileDes,outFileDes;
inFileDes=open("in",O_RDWR | O_CREAT,S_IRUSR | S_IWUSR);
outFileDes=open("out",O_RDWR | O_CREAT,S_IRUSR | S_IWUSR);
for(i=0;i<3;i++)
{
if((pid=fork())==0)
{
switch(i)
{
case 0:
dup2(outFileDes,1);
execl("/bin/ls","ls","-al",0);
break;
case 1:
// originally:
dup2(outFileDes,0); // dup2(outFileDes,1);
dup2(inFileDes,1); // dup2(inFileDes,0);
execl("/bin/grep","grep","foo",0); //lines having foo
break;
case 2:
dup2(inFileDes,0);
execl("/bin/grep","grep","bar",0); //lines having foo & bar
break;
}
exit(-1); //in error
}
waitpid(pid,NULL,0);
}
close(inFileDes);
close(outFileDes);
return(0);
}