I want to output some data to a pipe and have the other process do something to the data line by line. Here is a toy example:
mkfifo pipe cat pipe& cat >pipe
Now I can enter whatever I want, and after pressing enter I immediately see the same line. But if substitute second pipe with echo
:
mkfifo pipe cat pipe& echo "some data" >pipe
The pipe closes after echo
and cat pipe&
finishes so that I cannot pass any more data through the pipe. Is there a way to avoid closing the pipe and the process that receives the data, so that I can pass many lines of data through the pipe from a bash script and have them processed as they arrive?
A named pipe, also called a FIFO, is a pipe identified by an entry in a file system's name space. FIFOs are created using mknod(2), mkfifo(3C), or the mknod(1M) command. They are removed using unlink(2) or the rm(1) command.
A FIFO file is a special kind of file on the local storage which allows two or more processes to communicate with each other by reading/writing to/from this file. A FIFO special file is entered into the filesystem by calling mkfifo() in C.
The named pipe is created with the mkfifo system call. A named pipe is much like a traditional pipe, created with the pipe system call. However, while pipe provides access via two file descriptors, the named pipe is accessed via the filesystem at a path. #include <sys/types.
Put all the statements you want to output to the fifo in the same subshell:
# Create pipe and start reader. mkfifo pipe cat pipe & # Write to pipe. ( echo one echo two ) >pipe
If you have some more complexity, you can open the pipe for writing:
# Create pipe and start reader. mkfifo pipe cat pipe & # Open pipe for writing. exec 3>pipe echo one >&3 echo two >&3 # Close pipe. exec 3>&-
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With