简体   繁体   中英

Pipe two shell commands in C

I'm trying to execute grep -o colour colourfile.txt | wc -w > newfile.txt grep -o colour colourfile.txt | wc -w > newfile.txt through a program in C, instead of using the command line.

This is what I have so far:

#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()) { means parent process not child process , see http://man7.org/linux/man-pages/man2/fork.2.html
  2. You should handle > like | use open()

The following code could work:

#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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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