我想模拟这个 Unix 命令:
cat file.txt | sort | tail -4
我遵循了该技术,但它不起作用,它仍然被阻止。 也许当有文件时我需要使用其他东西。 我使用了两个管道和两个进程,并且在一个进程中使用了两个 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);
}
}
}
这是文件.txt:
g
f
d
b
c
a
e
最佳答案
父进程永远不会关闭管道p1
所以它的 child 继续尝试阅读它。添加close(p1[0]); close(p1[1]);
之前execlp("tail", "tail", "-4", NULL);
.
另请注意,您不应该不 wait(NULL)
:当 file.txt 很大并开始填充管道缓冲区时,这是另一个等待发生的挂起。
关于c - 将 Unix 命令与 C 一起通过管道传输,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10374305/