簡體   English   中英

輸入重定向和管道

[英]Input redirection and pipes

我了解您要在其中運行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()?)。 我將不勝感激一些幫助。

謝謝。

但是,您將如何包括輸入和輸出重定向? 可以說我要貓<foo.txt | wc -l

在輸入重定向的情況下,您可以打開文件進行讀取,然后使用dup2(2)將文件描述符復制到標准輸入中。 stdin文件描述符為STDIN_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];
// ...

請注意,您的代碼沒有錯誤處理-沒有錯誤處理-這非常糟糕,因為當出現問題時,您將忽略它,並且代碼將以神秘的方式崩潰。 您調用的每個函數幾乎都可以返回錯誤。 考慮處理錯誤以向用戶清楚地指出哪里出了問題。

暫無
暫無

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

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