pgrep/pkill: Feature request: Allow selecting processes based on elapsed time + CPU usage
The idea is to allow pgrep
/pkill
to use the following as additional selection criteria:
-
Elapsed time: The wall-clock period of time that has passed since the process was started. This would at a minimum be expressed as a number of seconds, but allowing alternate time units as in
sleep(1)
would be nice. -
CPU usage: Percentage of the process's elapsed time that has been spent actively running on the CPU. (This is over the lifetime of the process, not over a short window of time.) In a single-CPU system, this would be a range of 0 to 100%, where the low end represents a process that has been mostly idle. In multi-CPU systems, it may or may not make sense to normalize this value down to a 0-100% range.
The selection would operate in terms of "give me processes that have time/usage above or below this number."
Use case 1: My company has a shared system with many users. They often use VS Code and Jupyter. Every so often, something will go wrong with one of these applications, causing it to begin consuming 100% CPU (one thread only). The user is none the wiser, and because the system has many CPUs, this does not cause noticeable performance degradation. It's not unusual to see a dozen or so such processes, with run times of several days/weeks.
With pgrep
/pkill
, I can match the process command lines exactly. But I don't want to kill processes that aren't hogging the CPU, because those are legitimately in use. I'd like to be able to kill processes with a specific command line, with an elapsed time above (say) three days, and with a lifetime CPU usage over 80%. And then put that in cron.daily
.
Use case 2: Sometimes, apt-get(8)
hangs in the course of performing an automatic system update. As long as it remains hanged, it will block further automatic updates, potentially leading to a security vulnerability due to an unpatched system. I want to kill the apt-get
process if it has been alive for more than, say, four hours---and definitely don't want to kill it otherwise!