Skip to content

Instantly share code, notes, and snippets.

@binaryphile
Created June 20, 2017 13:35
Show Gist options
  • Save binaryphile/32b2bd8612d0bb5a7acdec140bbda02f to your computer and use it in GitHub Desktop.
Save binaryphile/32b2bd8612d0bb5a7acdec140bbda02f to your computer and use it in GitHub Desktop.
file descriptor measurement tool
#!/usr/bin/env bash
fdsta_main () {
local num=${1:-5}
local user=${2:-$USER}
fds "$num" "$user"
}
fds() {
local num=$1
local user=$2
local -A fdh=()
local IFS=$IFS
local command
local count
local max
local old_IFS=$IFS
local open
local pid
local pids=()
local result
local results=()
local sum=0
read -rd '' -a pids <<<"$(ps -U "$user" -o pid | tail -n +2)" ||:
shopt -s nullglob
for pid in "${pids[@]}"; do
dir=/proc/$pid/fd
count=$(set -- $(wc -w <(echo "$dir"/*)); echo "$1")
(( count )) || continue
fdh[$pid]=$count
: $(( sum += $count ))
done
shopt -u nullglob
for pid in "${!fdh[@]}"; do
results+=( "$(printf '%s %s' "${fdh[$pid]}" "$pid")" )
done
IFS=$'\n'
results=( $(sort -rn <<<"${results[*]}") )
IFS=$old_IFS
pids=()
for result in "${results[@]}"; do
pids+=( "$(set -- $result; echo "$2")" )
done
printf ' FDS PID CMD\n----- ------ ---\n'
results=()
for pid in "${pids[@]:0:$num}"; do
command=$(ps -p "$pid" -o cmd=)
(( ${#command} > 300 )) && command=${command:0:300}...
results+=( "$(printf '%05s %06s %s' "${fdh[$pid]}" "$pid" "$command")" )
done
printf '%s\n\n' "${results[@]}"
printf '\nTotal file descriptors for user %s: %s\n' "$user" "$sum"
result=$(< /proc/sys/fs/file-nr)
open=$(set -- $result; echo "$1")
max=$(set -- $result; echo "$3")
printf 'System-wide open file descriptors: %s\n' "$open"
printf 'System-wide max file descriptors: %s\n\n' "$max"
}
strict_mode () {
case $1 in
'on' )
set -o errexit
set -o nounset
set -o pipefail
;;
'off' )
set +o errexit
set +o nounset
set +o pipefail
;;
* ) return 1;;
esac
}
return 0 2>/dev/null ||:
strict_mode on
fdsta_main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment