Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interprocess Communication via file

Tags:

linux

process

ipc

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?

like image 534
Amumu Avatar asked Jun 16 '12 09:06

Amumu


1 Answers

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.

like image 154
Zagorax Avatar answered Oct 13 '22 11:10

Zagorax