They are not exactly the same in the sense that calling pipe(2) not enough to implement the equivalent shell function | .
pipe(2) creates two file descriptors (end of read and end of write). But you need to do more to realize the functionality | .
A typical pipe creation sequence is as follows:
1) Create the end of the read and the end of the record using pipe(2) .
2) Create a child process using fork() .
3) Parent and child processes duplicate file descriptors using dup2() .
4) Both processes, each of which closes one end of the pipe (one end of the pipe that does not use each process).
5) One writes into the pipe, and the other reads from the pipe.
Consider a simple example to demonstrate this. In this case, you pass the file name as an argument, and the parent process - "greps" - the file that cat - child.
#include <stdio.h> #include <unistd.h> int main(int argc, char **argv) { int pipefd[2]; int pid; char *cat_args[] = {"cat", argv[1], NULL}; char *grep_args[] = {"grep", "search_word", NULL}; pipe(pipefd); pid = fork(); if (pid != 0) { dup2(pipefd[0], 0); close(pipefd[1]); execvp("grep", grep_args); } else { dup2(pipefd[1], 1); close(pipefd[0]); execvp("cat", cat_args); } }
This is equivalent to doing
cat file | grep search_word
on the shell.
PP
source share