I am using tail -f to follow the growth of a log file. I am having trouble finding a way to detect if the process that is writing to the log file (when it crashes or is otherwise terminated) is no longer accessing or writing to the file.

Here is the script I am using

tail -f log_file | while read LOGLINE
  echo -e "${LOGLINE}"
  if [[ "${LOGLINE}" == *ERROR* ]] ; then
  echo -e "ERROR FOUND : ${LOGLINE}\n"

  # handle the error here


What is the easiest and most efficient way to detect that the process writing to the log file has stopped (or that tail -f is no longer recieving input) and echo a message to screen alerting me of the event?

closed as off-topic by devnull, slm, jasonwryan, Thomas Nyman, Anthon Apr 27 '14 at 10:35

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question has been posted on multiple sites. Cross-posting is strongly discouraged; see the help center and community FAQ for more information." – devnull, slm, jasonwryan, Thomas Nyman, Anthon


At least if you are running Linux you are doing this backwards. You should use inotify to react to the file being written.

while inotifywait -qe modify filename


that will do.


To obtain the process IDs of all processes which have your log file open, use lsof:

lsof -Fp /path/to/your/logfle

Note that this will only show processes which actually have the file open. You may miss programs that keep the file closed except the brief instants when they actually need to write to it.

lsof is script-friendly and has many options. See man lsof.

Here is a script which will write a message to the screen once there are no processes with your log file open:

while lsof -Fp /tmp/mylogfile  >/dev/null
    sleep 1
echo "No processes have the log file open"

There is a catch to the above: your tail -f process will have the file open. You may want instead to show the message when the number of processes with that file open drops below two:

while [ "$(lsof -Fp /tmp/mylogfile | wc -l)" -ge 2 ]
    sleep 1
echo "There are less than two processes with the log file open"
  • On my laptop, lsof is making more than 27000 systems call at each loop. I don't know if it's considered clean scripting, nowadays things are changing so fast. – Emmanuel Apr 26 '14 at 23:01
PROC=apache2 # insert your process name here

while true; do
    pgrep $PROC > /dev/null # hides pgrep's output
    if [[ $? -ne 0 ]]; then
        echo "Call 911 $PROC died!" 1>&2 # redirects to stderr
    sleep 1

So call this something like lifealert.sh and run it in the background like so ./lifealert.sh &

When the if statement fires it will print to stderr, which you should see in your terminal while you're tailf-ing a file.

Not the answer you're looking for? Browse other questions tagged or ask your own question.