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 monitor_log_and_process.sh
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.
#!/bin/bash # Monitor log modification time and restart process if it was not updated for defined period of time # log file location log_file="/var/log/serial_app.log" # log process name and path process_bin="serialApp" process_loc="/usr/sbin" # maximum seconds after last modification date before issuing process restart ctime_max=60 # 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)" ctime_diff="$((ctime_current-ctime))" 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 fi else # start process ${process_loc}/${process_bin} fi
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
).