#include <unistd.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
int f1[2], f2[2];
char buff;
if(pipe(f1) != -1);
printf("Pipe1 allright! \n");
if(pipe(f2) != -1);
printf("Pipe2 allright \n");
if(fork()==0)
{
close(1);
dup(f1[1]);
close(0);
execlp("ls", "ls", "-l", NULL);
}
else
{
if(fork()==0)
{
close(0);
dup(f1[0]);
close(1);
dup(f2[1]);
execlp("grep", "grep", "^d", NULL);
}
else
{
if(fork()==0)
{
close(0);
dup(f2[0]);
execlp("wc", "wc", "-l", NULL);
}
}
}
return 0;
}
I am trying to do ls -l | grep ^d | wc -l in C.
I tried everythig…
What is wrong? 🙁
Output: Pipe1 allright!, Pipe2 allright!
Ps. Your post does not have much context to explain the code sections; please explain your scenario more clearly.
There are several problems with your code:
I assume this should be a real error check, so please remove the
;in theifline.Running your program after that you will notice, that the
grepandwccommands are still there, they don’t terminate. Check this with theps(1)command. Thelscommand seems to have terminated.Let’s assume, the pids of the four processes are :
Looking into
/proc/9002/fdyou will see, that filehandle 0 (stdin) is still open for reading:And looking around, who has this handle still open with
you will see, that many handles to this pipe are open: both
grepandwchave two of them open. Same is true for the other pipe handles.Solution:
You have to close the pipe handles after
duprigorously. Look here: