-
Notifications
You must be signed in to change notification settings - Fork 9
/
collect-ps-periodically
executable file
·58 lines (53 loc) · 1.48 KB
/
collect-ps-periodically
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#!/usr/bin/env bash
# Collects the output of 'ps' periodically, and dumps them to
# the given directory, with one file per dump.
#
# ## Usage syntax
#
# collect-ps-periodically <DUMP DIRECTORY> <INTERVAL>
#
# `DUMP DIRECTORY` specifies where to dump to. This directory must
# already exist.
#
# `INTERVAL` specifies the interval between dumps, in seconds. You
# can also specify a unit suffix, e.g. `5m` (5 minutes) or `2h` (2 hours).
#
# ## Example
#
# Create a dump directory and run the script in the background,
# collecting every 5 minutes:
#
# mkdir ~/ps-dumps
# nohup collect-ps-periodically ~/ps-dumps 5m &
#
# At any point, feel free to stop the script...
#
# ps aux | grep collect-ps-periodically
# kill <PID>
#
# ...and tar the dump directory and send it to someone for analysis:
#
# tar -czf ps-dumps.tar.gz ~/ps-dumps
set -e
TARGET_DIR="$1"
INTERVAL="$2"
if [[ -z "$TARGET_DIR" || -z "$INTERVAL" ]]; then
echo 'Usage: collect-ps-periodically <DUMP DIRECTORY> <INTERVAL>'
exit 1
fi
function cleanup()
{
# shellcheck disable=SC2155
local PIDS=$(jobs -p)
if [[ -n "$PIDS" ]]; then
# shellcheck disable=SC2086
kill $PIDS || true
fi
}
trap cleanup EXIT
while true; do
DATE=$(date --rfc-3339=seconds)
ps -Ao 'user,pid,ppid,lwp,%cpu,%mem,rss,maj_flt,start_time,wchan,stat,flag,nlwp,cmd' --forest > "$TARGET_DIR/$DATE procs.txt"
ps -ALo 'user,pid,ppid,lwp,%cpu,%mem,rss,maj_flt,start_time,wchan,stat,flag,cmd' > "$TARGET_DIR/$DATE threads.txt"
sleep "$INTERVAL"
done