Skip to content

Instantly share code, notes, and snippets.

@gjaekel
Created September 16, 2021 08:03
Show Gist options
  • Select an option

  • Save gjaekel/b1570a8ed475bd1ff6fe53fe13828373 to your computer and use it in GitHub Desktop.

Select an option

Save gjaekel/b1570a8ed475bd1ff6fe53fe13828373 to your computer and use it in GitHub Desktop.
Display Number of Open Filehandles in total or grouped by kind of Files, Sockets, Pipes, Anon_INodes, for all processes or a ceratain PID
#!/bin/bash
#
# 20141126/gj
# 20150219/gj pipes
# 20190225/gj 'all' command
# 20191107/gj add anon_inode
# 20191007/gj get fd stats once
# 20200616/gj get limits
# 20200806/gj get limits via /etc/security/limits.conf because smnpd is startet with lower limits
# 20200919/gj skip comments in limits.conf
COUNTHANDLES() { # $1: PID
[ "$OPENTOTAL" ] && return # evaluate once
# evaluate all symbolic links
while read _ _ NAME; do
NAME=${NAME:1:-1}
case "$NAME" in
'anon_inode:'*) ((OPENANON_INODES++)) ;;
'pipe:'*) ((OPENPIPES++)) ;;
'socket:'*) ((OPENSOCKETS++)) ;;
*) ((OPENFILES++));;
esac
done < <(eval stat /proc/${1:-\{1..9\}*}/fd/* -c "%N" 2>/dev/null)
OPENTOTAL="$((OPENFILES + OPENSOCKETS + OPENPIPES + OPENANON_INODES))"
}
READLIMIT() { # $1: KIND
local KIND="$1"; shift
sed 's/^[^#].*'$KIND'.*nofile\W*\(.*\)/\1/gp' -n /etc/security/limits.conf
}
DISPLAY() { #1: WHICH, #2: PID
COUNTHANDLES $2
OPENSOFTLIMIT="$(READLIMIT soft)"
OPENHARDLIMIT="$(READLIMIT hard)"
if [ "$1" ]; then
echo "${!1}"
else
echo "total:$OPENTOTAL files:$OPENFILES sockets:$OPENSOCKETS pipes:$OPENPIPES anon_inodes:$OPENANON_INODES limit:$OPENSOFTLIMIT hard:$OPENHARDLIMIT"
fi
}
KIND="$1"; shift
PID="$1"; shift
case "$KIND" in
'a'*) DISPLAY OPENANON_INODES $PID;;
'f'*) DISPLAY OPENFILES $PID;;
'h'*) DISPLAY OPENHARDLIMIT $PID;;
'l'*) DISPLAY OPENSOFTLIMIT $PID;;
'p'*) DISPLAY OPENPIPES $PID;;
's'*) DISPLAY OPENSOCKETS $PID;;
't'*) DISPLAY OPENTOTAL $PID;;
[0-9]*|'')
PID=$KIND; KIND=''
DISPLAY '' $PID
;;
*)
cat >&2 <<-EOT
syntax : $0 <f[iles],s[ocktes],p[ipes],a[non_inodes],l[imit],h[ardlimit]> [pid]
$0 t[otal] [pid]
$0 pid
$0
purpose: display number of open files for a kind or for all kinds
EOT
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment