Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid echo closing FIFO named pipes? - Funny behavior of Unix FIFOs

Tags:

bash

unix

echo

pipe

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?

like image 858
user1084871 Avatar asked Dec 07 '11 04:12

user1084871


People also ask

How pipe and FIFO are created in Unix?

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.

What is FIFO in UNIX programming?

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.

What does mkfifo create named pipe?

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.


1 Answers

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>&- 
like image 113
Mark Edgar Avatar answered Oct 23 '22 06:10

Mark Edgar