简体   繁体   English

输入重定向和管道

[英]Input redirection and pipes

I understand piping where you want to run a command like ls -l | 我了解您要在其中运行ls -l等命令的管道。 wc -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);
}

But, how would you include input and output redirection? 但是,您将如何包括输入和输出重定向? lets say I want to cat < foo.txt | 可以说我要猫<foo.txt | wc -l wc -l

I understand the first fork needs to be modified, but I don't understand what is needed (another dup2()?). 我知道第一个fork需要修改,但是我不知道需要什么(另一个dup2()?)。 I would greatly appreciate some help. 我将不胜感激一些帮助。

Thanks. 谢谢。

But, how would you include input and output redirection? 但是,您将如何包括输入和输出重定向? lets say I want to cat < foo.txt | 可以说我要猫<foo.txt | wc -l wc -l

In the case of input redirection, you open the file for reading, and then use dup2(2) to duplicate the file descriptor into standard input. 在输入重定向的情况下,您可以打开文件进行读取,然后使用dup2(2)将文件描述符复制到标准输入中。 The file descriptor of stdin is STDIN_FILENO , defined in unistd.h . stdin文件描述符为STDIN_FILENO ,在unistd.h定义。 So, something like this: 因此,如下所示:

#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];
// ...

Note that your code doesn't have error handling - not one - this is very bad because when something goes wrong, you will ignore it and the code will crash in mysterious ways. 请注意,您的代码没有错误处理-没有错误处理-这非常糟糕,因为当出现问题时,您将忽略它,并且代码将以神秘的方式崩溃。 Pretty much every function you called can return with an error; 您调用的每个函数几乎都可以返回错误。 considering handling the error to clearly show to the user what went wrong where. 考虑处理错误以向用户清楚地指出哪里出了问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM