2013-03-22 57 views
0

我想实现多个管道用C像碳多重管道

ls - al | less | wc 

我与创建管道的麻烦。我有一个应该与管道创建的过程和连接它们的循环:

for(i=0;i<num_cmds;i++){ 
    create_commands(cmds[i]); 
} 

create_commands()功能看起来像这样

void create_commands (char cmd[MAX_CMD_LENGTH]) // Command be processed 
{ 
    int pipeid[2]; 
    pipe(pipeid); 

    if (childpid = fork()) 
    { 
     /* this is the parent process */ 
     dup2(pipeid[1], 1); // dup2() the write end of the pipe to standard output. 
     close(pipeid[1]); // close() the write end of the pipe 

     //parse the command 
     parse_command(cmd, argvector); 

     // execute the command 
     execvp(argvector[0], argvector); 

     close(1); // close standard output 
    } 
    else 
    { 
     /* child process */ 
     dup2(pipeid[0], 0); // the read end of the pipe to standard input 
     close(pipeid[0]); // close() the read end of the pipe 
    } 

} 

但是,这并不工作,我得到我的标准输入和stdout搞砸了。 任何人都可以请指点我做错了什么?

预先感谢您!

回答

1

popen()函数执行由string命令指定的命令。它在调用程序和执行的命令之间创建一个管道,并返回一个指向可用于读取或写入管道的流的指针。

#include <stdio.h> 
int main(int argc, char *argv[]) 
{ 

    FILE *fp; 
    int status; 
    int PATH_MAX = 1024; 
    char path[PATH_MAX]; 
    fp = popen("ls -al | less | wc", "r"); 
    if (fp == NULL) 
     /* Handle error */; 


    while (fgets(path, PATH_MAX, fp) != NULL) 
     printf("%s", path); 


    status = pclose(fp); 
    if (status == -1) { 
    /* Error reported by pclose() */ 
    } else { 
    /* Use macros described under wait() to inspect `status' in order 
     to determine success/failure of command executed by popen() */ 
    } 

} 

您可以使用预设的字符串POPEN()中被调用,你也可以用你的argv []参数像you'ld用管道输送。

popen()为您提供了一个管道,一个FIFO先进先出流,popen还将STDOUT反馈回您的程序。

这里是()的手册页POPEN: http://linux.die.net/man/3/popen

+0

感谢您指出的popen(),不幸的是我需要使用管道()和叉()系统调用。 – 2013-03-22 22:58:08

+1

这样做的一种方法是使用组合: 1)使用管道创建管道 2)使用fork创建子进程,在您的情况下:less/vim 3)使用dup2强制子进程使用管道作为其标准输入或输出通道, 4)使用exec执行新程序。 – 2013-03-22 23:07:01