Idle Time of a Process in Linux

How do I write a shell script to get a given process idle time?

Here you are:

#! /bin/bash
# Assumptions:
# Process is attached to a tty.
#

[[ -z "$1" ]] && echo "Usage: $0 pid" && exit 1

[[ "$1" != +([0-9]) ]] && echo "$1 is not a valid pid" && exit 1

PID="$1"
W=$(which w)
PS=$(which ps)
SED=$(which sed)
AWK=$(which awk)
TTY=$($PS -o tty4 $PID)
TTNo=$(echo "$TTY" | $SED -e '/TTY/d')

TIME=$($W | $SED -n -e "/pts\/$TTNo/p" | $AWK '{ print $5 }')

echo $PID has been idle for $TIME

How can I check a user's idle time in Linux?

The idle time measured by w is simply indicating how long since something was typed on the terminal a process is attached to. As seen e.g. here this is inaccurate for actually measuring user activity, since they might be using solely graphical input and not typing anything.

If your users are logged into an X11 session, the X client library has its own idle timer which can be queried; see e.g. User idle time being reset to 0 after 30 secs on Linux

Cloud monitoring systems appear to examine things like CPU load and network traffic to decide when to declare an instance as idle. They probably have a baseline of system processes which can be ignored, and then simply add a tick whenever a non-system process is detected.

For your use case, perhaps a simple network monitoring tool would be the easiest to set up. If your users are always logged in over SSH, check for traffic on port 22; if there is none over several minutes, the instance is idle. For X11 sessions, something similar could be set up for X protocol traffic (ports typically in the range from 6000 up).



Related Topics



Leave a reply



Submit