named pipes on Unix

    I read about them for a long time, even when I was studying the basics of Unix, but somehow there was no need to work with them. And so, need arose.

    A certain program (for example, foo) is not able to write output to stdout, only to a file. Even "-" as a file name just creates a file with the name "-" [most smart programs under unix know that a single minus instead of the file name means output to stdout]. Similarly, it rejects / dev / stdout.

    Another program that processes the results of the first, say bar, reads from stdin and writes to stdout. (to be precise, the first is a special kind of tracer that gives a binary dump, and the second is a converter that prints them in human-readable form).

    It is necessary to combine them into a conveyor.

    An ugly option is to use a regular file. I wrote it down, read it.

    There is a much more beautiful option - these are named pipes . Since the pipe has a name, we can transfer it as a file to the first program, and then transfer the contents to another.

    It looks like this:

    mkfifo mypipe
    cat mypipe | bar &
    foo mypipe &
    rm mypipe
    



    The pipe in the file system looks like this:
    ls -l mypipe
    prw-r - r-- 1 root root 0 May 24 12:23 mypipe
    

    (emphasis on the letter 'p' as the first character).

    How it works? In fact, fifo aka named pipe is an “ordinary pipe”, something like that encoded with the "|" stick. However, it has a NAME and this name can be indicated wherever a file is required.

    A program that writes to a named pipe behaves with it like a file. Those. writes to himself and writes. A program that reads is similar. Reads to himself and reads. Reading goes in the order the recording was made (FIFO - first in first out). The provisions regarding the pipe (left / right) are determined by those who read and who write.

    An important feature of the pipe is the ability to slow down the reading / squeaking program if the buffer is empty / full.

    Consider the example of reading. The program writes one line per second on the pipe. The reader program reads as fast as possible. The program “reads out” everything that was in the buffer and sends the next request. The kernel delays this request until the data appears. Thus, you do not have to worry about synchronization - data will appear, the handler program will get control back from read () and process the next batch of data.

    Also popular now: