0

我想模拟这个 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); 
            }             
  }
}

这是 file.txt :

g
f
d
b
c
a
e
4

1 回答 1

1

父进程永远不会关闭管道p1,因此它的子进程会继续尝试读取它。在. close(p1[0]); close(p1[1]);_execlp("tail", "tail", "-4", NULL);

另请注意,您不应该 wait(NULL)当 file.txt 很大并开始填充管道缓冲区时,这是另一个等待发生的挂起。

于 2012-04-29T17:56:31.263 回答