I want to simulate this Unix command :
cat file.txt | sort | tail -4
I followed the technique, but it does not work, it remains blocked. Maybe i need to use something else when there are files. I used two pipes, and two processes and i used two DUP in a single process, maybe that's wrong.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main()
{
int p1[2];
int p2[2];
if(pipe(p1))
{
perror("pipe1");
exit(0);
}
if(pipe(p2))
{
perror("pipe2");
exit(0);
}
switch(fork())
{
case -1: perror(" fork1 error ");
exit(0);
case 0: close(STDOUT_FILENO);
(void)dup(p1[1]);
close(p1[1]);
close(p1[0]);
execlp("cat", "cat", "file.txt", NULL);
exit(0);
default:
switch(fork())
{
case -1: perror(" fork2 error ");
exit(0);
case 0: close(STDIN_FILENO);
(void)dup(p1[0]);
close(p1[1]);
close(p1[0]);
close(STDOUT_FILENO);
(void)dup(p2[1]);
close(p2[1]);
close(p2[0]);
execlp("sort", "sort", NULL);
exit(0);
default:
wait(NULL);
close(STDIN_FILENO);
(void)dup(p2[0]);
close(p2[0]);
close(p2[1]);
execlp("tail", "tail", "-4", NULL);
}
}
}
this is the file.txt :
g
f
d
b
c
a
e
The parent process never closes the pipe p1
so its child keep trying to read on it. Add close(p1[0]); close(p1[1]);
close(p1[0]); close(p1[1]);
before the execlp("tail", "tail", "-4", NULL);
.
Also note that you should not wait(NULL)
: this is another hang waiting to happen when file.txt is big and starts to fill the pipe buffer.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.