Making a Process Look Like a File with Named Pipes


You want a process to intercept all access to a file. For instance, you want to make your ~/.plan file a program that returns a random quote.


Use named pipes. First create one, probably from your shell:

% mkfifo /path/to/named.pipe

Here’s a reader for it:

open(FIFO, "< /path/to/named.pipe")         or die $!;
while (<FIFO>) {
    print "Got: $_";

Here’s a writer for it:

open(FIFO, "> /path/to/named.pipe")         or die $!;
print FIFO "Smoke this.\n";


A named pipe, or FIFO as they are also known, is a special file that acts as a buffer to connect processes on the same machine. Ordinary pipes also allow processes to communicate, but those processes must have inherited the filehandles from their parents. To use a named pipe, a process need know only the named pipe’s filename. In most cases, processes don’t even need to be aware that they’re reading from a FIFO.

Named pipes can be read from and written to just as though they were ordinary files (unlike Unix-domain sockets as discussed in Chapter 17). Data written into the FIFO is buffered up by the operating system, then read back in the order it was written in. Because a FIFO acts as a buffer to connect processes, opening one for reading will block until another process opens it for writing, and vice versa. If you open for read and write using the +< mode to open, you won’t block (on most systems) because your process could be both reader and writer. ...

Get Perl Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.