Will the unix pipes (|) and the pipe we create using "pipe (int pipefd [2])" in c be the same?

Is unix pipe (|), which pipelines the output of the process to another, and the pipe that we create using "pipe (int pipefd [2])" in c used for interprocess communication is the same?

+8
c unix pipe
source share
3 answers

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.

+5
source share

Pipe shell | implemented using the pipe(2) and dup2(2) system calls.

See Unix Pipes .

+6
source share

Syscall pipe(2) used by pipe wrappers with operator |

| is a shell implementation, it uses syscall pipe() extensively.

0
source share

All Articles