将 Unix 命令与 C 一起管道



我想模拟这个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因此其子进程不断尝试读取它。在execlp("tail", "tail", "-4", NULL);之前添加close(p1[0]); close(p1[1]);

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

最新更新