2016-01-24 70 views
1

我了解管道要运行的命令,如ls -l | wc -l:输入重定向和管道

int pipes[2]; 
pipe(pipes); 

if (fork() == 0){ //first fork 
    dup2(pipes[1],1); 
    close(pipes[0]); 
    close(pipes[1]); 

    execvp(arr1[0], arr1); //arr1[0] = "ls" and arr1[1] = "-l" and arr1[2] = 0 
    perror("Ex failed"); 
    exit(1); 
} 

if (fork() == 0){ //2nd fork 
    close(pipes[1]); 
    dup2(pipes[0],0); 
    close(pipes[0]); 

    execvp(arr2[0], arr2); //arr2[0] = "wc" and arr2[1] = "-l" and arr2[2] = 0 
    perror("Ex failed"); 
    exit(1); 
} 

但是,如何包含输入和输出重定向?可以说我想猫< foo.txt | wc -l

我知道第一个fork需要修改,但我不明白需要什么(另一个dup2()?)。我将不胜感激一些帮助。

谢谢。

+0

你希望用'dup2(pipes [1],[1])完成什么?这是无效的语法;我认为你的意思是'dup2(管道[1],STDOUT_FILENO);'? –

+0

这是一个错字。我会解决它。 – user5832523

回答

0

但是,如何包含输入和输出重定向?可以说我 想要猫< foo.txt | wc -l

在输入重定向的情况下,打开文件进行读取,然后使用dup2(2)将文件描述符复制到标准输入中。文件描述符stdinSTDIN_FILENO,在unistd.h中定义。所以,这样的事情:

#include <unistd.h> 
#include <fcntl.h> 
#include <stdio.h> 
#include <stdlib.h> 

// ... 

filename = "foo.txt"; 
int fd; 
if ((fd = open(filename, O_RDONLY)) == -1) { 
    perror("open %s: %s\n", filename, strerror(errno)); 
    exit(EXIT_FAILURE); 
} 
if (dup2(fd, STDIN_FILENO) == -1) { 
    perror("dup2: %s -> stdin: %s\n", filename, strerror(errno)); 
    exit(EXIT_FAILURE); 
} 
if (close(fd) == -1) { 
    perror("close %s: %s\n", filename, strerror(errno)); 
    exit(EXIT_FAILURE); 
} 

// Now, reading from stdin will read from the file. 
// Do the normal pipe operations here. 

int pipes[2]; 
// ... 

请注意,您的代码没有错误处理 - 没有一个 - 这是非常糟糕的,因为出问题的时候,你会忽视它的代码将在神秘的方式崩溃。几乎每个你调用的函数都会返回一个错误;考虑处理错误,以清楚地向用户展示哪里出了什么问题。

+0

这似乎并不奏效。我完全按照你的建议做了。打开(),dup2()并关闭,然后我的两个叉子保持不变。叉中是否需要额外的代码? – user5832523

+0

@ user5832523分叉的代码应该保持不变。请发布您声称无法使用的完整工作,可编译的代码。 –