Interprocess Communication via file

Issue

When I echo into files at some arbitrary locations in Linux, i.e. echo > /tmp/file, some running processes respond. Is this IPC via file pipe?

Does this mean a running process always open the file to be read? But so, how can the file be written, since the file stream is locked by by its own process?

Solution

If you want use a file to communicate with another process, you should have a look at man fifo.

I’ll report here just the first lines:

NAME
       fifo - first-in first-out special file, named pipe

DESCRIPTION
       A FIFO special file (a named pipe) is similar to a pipe, except that it
       is accessed as part of the file system.  It can be opened  by  multiple
       processes  for  reading or writing.  When processes are exchanging data
       via the FIFO, the kernel passes all data internally without writing  it
       to the file system.  Thus, the FIFO special file has no contents on the
       file system; the file system entry merely serves as a  reference  point
       so that processes can access the pipe using a name in the file system.

I think this is what you need.

Just think to it as a buffer. It must be opened both for reading and for writing by different process. The process who’s reading will be blocked until the writing process doesn’t write on it. When the writing process finish to write, close the file and that is the green light for the reading process to start empty the buffer. It’s a FIFO, so the first line written will be the first line read. Then the writing process can open it again and they start again.

You can create a FIFO with mkfifo. Have a look to man mkfifo.

Answered By – Zagorax

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published