簡體   English   中英

將Unix命令與C一起管道傳輸

[英]Pipe Unix commands together with 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); 
            }             
  }
}

這是file.txt:

g
f
d
b
c
a
e

父進程從不關閉管道p1因此其子進程繼續嘗試讀取它。 添加close(p1[0]); close(p1[1]); close(p1[0]); close(p1[1]); execlp("tail", "tail", "-4", NULL);

還要注意的是,你應該wait(NULL)這又是一個掛在等待時file.txt的是大事要發生,並開始填充管道緩沖區。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM