[英]Pipe Unix commands together with C
I want to simulate this Unix command : 我想模拟这个Unix命令:
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. 我使用了两个管道和两个进程,并且在一个进程中使用了两个DUP,也许那是错误的。
#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 : 这是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. 父进程从不关闭管道p1
因此其子进程继续尝试读取它。 Add close(p1[0]); close(p1[1]);
添加close(p1[0]); close(p1[1]);
close(p1[0]); close(p1[1]);
before the execlp("tail", "tail", "-4", NULL);
在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. 还要注意的是,你不应该wait(NULL)
这又是一个挂在等待时file.txt的是大事要发生,并开始填充管道缓冲区。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.