summaryrefslogtreecommitdiff
path: root/offlineimap-killer.sh
blob: 91f95096f4ba669f9c45a4db9990e34be8dcfca0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/bin/bash
# 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)
		if [[ "$uptime" -gt "$pid" ]]; then
			printf 'Killing %d which has been running for %d seconds' "$pid" "$uptime"
			kill -9 "$pid"
		fi
	done
}

main "$@"