Sometimes it is important to monitor log file modification time to restart the writing process when the file was not modified for defined period of time. I have already described how to check file metadata using stat utility which can be used to solve this task, but today I want to take advantage of the plain ls command.

The following will stop serialApp if the serial_app.log file wasn’t modified for at least 60 seconds. It will perform only one operation at time, so the process will be started on the consequent script execution after it was killed.

# Monitor log modification time and restart process if it was not updated for defined period of time

# log file location

# log process name and path

# maximum seconds after last modification date before issuing process restart

# check if process is running
process="$(pgrep ${process_bin})"
if [ -n "${process}" ]; then
  # check last log modification time
  ctime="$(ls ${log_file} --time=ctime -l --time-style=+%s | awk '{ print $6 }')"
  ctime_current="$(date +%s)"
  if [ "${ctime_diff}" -gt "${ctime_max}" ]; then
    # kill process as the log file was not modified for at least for $ctime_max
    kill -9 $process
  # start process

This is very simple and naive solution, but can be easily extended to check multiple processes (for loop), use application path (ps ax instead of pgrep), log performed operations (using logger) and start process in the same run (additional variable).