#!/bin/bash # Copyright (C) 2014-2015 Luke Shumaker # Usage: offlineimap-killer LIMIT # # Kills any instance of offlineimap that has been running longer than # LIMIT seconds. pid_uptime() { local pid=$1 local sec_uptime=$(cut -d ' ' -f1 /proc/uptime) local tic_started_at tic_started_at=$(cut -d ' ' -f 22 /proc/${pid}/stat 2>/dev/null) || { echo 0; return 0; } local tic_per_sec=$(getconf CLK_TCK) bc <<<"${sec_uptime} - (${tic_started_at}/${tic_per_sec})" } main() { declare -i limit=$1 local pids=($(pgrep -x offlineimap)) local pid for pid in "${pids[@]}"; do declare -i uptime=$(pid_uptime $pid|cut -d. -f1) if [[ "$uptime" -gt "$pid" ]]; then printf 'Killing %d which has been running for %d seconds' "$pid" "$uptime" kill -9 "$pid" fi done } main "$@"