Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Named Pipes (FIFOs) on Unix with multiple readers

Tags:

unix

fifo

I have two programs, Writer and Reader.

I have a FIFO from Writer to Reader so when I write something to stdin in Writer, it gets printed out to stdout from Reader.

I tried doing this with TWO Readers open, and I got output to stdout from only one of the two Reader programs. Which Reader program Unix chooses to print stdout from seemed to be arbitrary each time I run this, but once it chooses one of the programs, each output to stdout gets printed from the same Reader program.

Does anyone know why this happens?

If I have two WRITER programs, they both write to the same pipe okay.

like image 424
Vlad the Impala Avatar asked Oct 28 '09 00:10

Vlad the Impala


People also ask

Can a pipe have multiple readers?

The kernel maintains exactly ONE pipe object for each FIFO special file at any time. Unlike sockets, it's not possible to broadcast data to multiple readers using named pipes. Unlike anonymous pipes which exist as long as the process exists, a named pipe can exist as long as the file exists in the file system.

Can multiple processes write to the same named pipe?

Yes, multiple processes can read from (or write to) a pipe. But data isn't duplicated for the processes.

What are named pipes in Unix?

Named pipe is meant for communication between two or more unrelated processes and can also have bi-directional communication. Already, we have seen the one-directional communication between named pipes, i.e., the messages from the client to the server.

What is the difference between how named pipes are implemented on Unix vs Windows systems?

One difference that I know of, is that named pipes under Linux are actual entries in the filesystem (you'll see it in a directory listing, they have a special type), whereas on Windows they are stored in some magical repository somewhere (they are all accessed via the path "\\. \pipe\".


1 Answers

The O in FIFO means "out". Once your data is "out", it's gone. :-) So naturally if another process comes along and someone else has already issued a read, the data isn't going to be there twice.

To accomplish what you suggest you should look into Unix domain sockets. Manpage here. You can write a server which can write to client processes, binding to a filesystem path. See also socket(), bind(), listen(), accept(), connect(), all of which you'll want to use with PF_UNIX, AF_UNIX, and struct sockaddr_un.

like image 192
asveikau Avatar answered Sep 19 '22 22:09

asveikau