簡體   English   中英

在C中管道兩個shell命令

[英]Pipe two shell commands in C

我正在嘗試執行grep -o colour colourfile.txt | wc -w > newfile.txt grep -o colour colourfile.txt | wc -w > newfile.txt通過C中的程序,而不是使用命令行。

這是我到目前為止:

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

int main (void) {
    int fd[2];

    pipe(fd);

    if (fork()) {
        // Child process
        dup2(fd[0], 0); // wc reads from the pipe
        close(fd[0]);
        close(fd[1]);
        execlp("wc", "wc", "-w", ">", "newfile.txt", NULL);
    } else {
        // Parent process
        dup2(fd[1], 1); // grep writes to the pipe
        close(fd[0]);
        close(fd[1]);
        execlp("grep", "grep", "-o", "colour", "colourfile.txt", NULL);
    }
    exit(EXIT_FAILURE);
}
  1. if (fork()) {表示parent process不是child process ,請參閱http://man7.org/linux/man-pages/man2/fork.2.html
  2. 你應該處理>喜歡| 使用open()

以下code可以工作:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>

int main (void) {
  int pipefd[2];
  pipe(pipefd);

  if (fork()) {
    // Child process
    dup2(pipefd[0], 0); // wc reads from the pipe
    close(pipefd[0]);
    close(pipefd[1]);
    int fd = open("newfile.txt", O_CREAT|O_TRUNC|O_WRONLY, S_IRUSR|S_IWUSR);
    dup2(fd, 1);
    close(fd);
    execlp("wc", "wc", "-w", NULL);
  } else {
    // Parent process
    dup2(pipefd[1], 1); // grep writes to the pipe
    close(pipefd[0]);
    close(pipefd[1]);
    execlp("grep", "grep", "-o", "colour", "colourfile.txt", NULL);
  }
  exit(EXIT_FAILURE);
}

暫無
暫無

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

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