Search code examples
bashinterprocess

Process communication through file in bash


I am doing bash scripting and want to set up communication between two processes using write to file. The walkthrough of the program will be:

  1. Process 1 opens file "file.txt" and writes some input specified by user in terminal
  2. Process 2 opens same file from other end and constantly reads it for update.
  3. If process 2 finds an update, it displays the output to the user.

Currently I am stuck at determining when the file has been updated and to store the updated part of the file (in this case the last line) in a variable.

Any help will be appreciated!

P.S. assume both process scripts are in the same location and are being run on different terminals.

Update

As some have suggested using named pipes with textfile being the pipe. I am running the processes on a cluster sharing the filesystem and the processes can be on any two nodes. So commands sent by process 1 is written to the file and is read by process 2 on a different node. Named pipes, on the other hand, requires both processes to be stored locally.


Solution

  • I was able to solve the problem with the following code:

    Process 2 reading the file for updates:

    filename="testfile.txt"
    tail -n 0 -F $filename | \
    while read LINE
    do
    echo "$LINE"
    done
    

    Process 1 writes to the file using simple >>

    The tail command is what solved my issue.