2010-09-04 56 views

回答

2

您也可以使用pipe(2,3p)。創建管道,分叉,將管道的相應末端複製到孩子的FD 0或FD 1上,然後執行exec。

25

前兩個命令的一個小例子。您需要使用pipe()函數創建一個管道,該函數將在ls和grep之間以及grep和more之間的其他管道之間移動。 dup2做的是將文件描述符複製到另一個文件描述符中。管道通過將fd [0]中的輸入連接到fd [1]的輸出來工作。您應該閱讀管道和dup2的手冊頁。如果您有其他疑問,我可以稍後嘗試並簡化示例。

#include <sys/types.h> 
#include <unistd.h> 
#include <stdio.h> 
#include <string.h> 
#include <errno.h> 

#define READ_END 0 
#define WRITE_END 1 

int 
main(int argc, char* argv[]) 
{ 
    pid_t pid; 
    int fd[2]; 

    pipe(fd); 
    pid = fork(); 

    if(pid==0) 
    { 
     printf("i'm the child used for ls \n"); 
     dup2(fd[WRITE_END], STDOUT_FILENO); 
     close(fd[WRITE_END]); 
     execlp("ls", "ls", "-al", NULL); 
    } 
    else 
    { 
     pid=fork(); 

     if(pid==0) 
     { 
      printf("i'm in the second child, which will be used to run grep\n"); 
      dup2(fd[READ_END], STDIN_FILENO); 
      close(fd[READ_END]); 
      execlp("grep", "grep", "alpha",NULL); 
     } 
    } 

    return 0; 
} 
+0

它可以只使用一個fork()和使用原始過程無論是LS或grep的,但還有我會留給你加以改進:P – theprole 2010-09-04 17:40:40

+0

我們應該怎麼管的grep的輸出越多。這只是把兩個過程正確地對準? – CanCeylan 2012-02-12 23:03:02

+1

不應該關閉grep的WRITE_END和ls的READ_END(與您所做的相反)? – 2015-05-10 11:45:05