Home > Enterprise >  What exactly happens when I pipe an output?
What exactly happens when I pipe an output?

Time:10-18

A pipe in Bash takes the standard output of one process and passes it as standard input into another process. Bash scripts support positional arguments that can be passed in at the command line.

I am working with Linux commands and pipes have always come up. What does it mean to pipe the standard output of one process? I understand that the output will be sent to the next command in the pipeline but how? How exactly does it happen? Why does variables created in a sub shell not be piped?

CodePudding user response:

What does it mean to pipe the standard output of one process?

It means to execute pipe system call. Then, fork one process, execute dup2 system call to duplicate file descriptor representing standard output stream to one of the file descriptors returned by pipe. Then, fork the second process, do the same dup2 but with the standard output file descriptor and the other file descriptor returned by pipe.

but how? How exactly does it happen?

Calling write system call from one process on one of the file descriptors returned by pipe system call, it executes a handler for the pipe, a kernel function, that takes the content of the buffer from userspace process and places it in a circular hold buffer.

When the other process executes read system call on the other file descriptors returned by pipe system call, the kernel function reads the element from the pipe circular hold buffer and copies data to the buffer given by the user, and advances the hold buffer.

Can I pipe contents of a variable? Can you include this in your answer?

You can execute a process that writes the content of the variable to standard output and connect the process to a pipe. I.e. echo "$var" |.

  •  Tags:  
  • bash
  • Related