Sometimes programs will lock up in the background and cause high CPU usage. Is there any way I can programmatically ascertain which process is causing the highest CPU load at the moment and kill it?
How to automatically kill the process with the highest CPU load
killprocesstop
Best Answer
There are a family of Unix commands that will probably serve you better if you're aware of them for this type of work.
You can use these tools to make your "attacks" more targeted, especially in situations where you know the misbehaving process by name(s).
killall
I have a recurring issue with Chrome where it eventually needs to be dealt with by killing it. I usually do this command to eradicate all of them.
pgrep & pkill
But I could do this as well, to deal with only the newest process:
Killing based on your command line
You can also add the
-f
switch to reach those processes that have long path arguments that you'd rather match on, instead of just their executable's name.For example, say I had these processes:
They're just Bash shells with their ARGV0 set to those names. Incidentally I made those processes using this trick:
Going after friends
But say I have a lot of them, and I only want to go after a particular set of them because they have "friend" in their command lines. I could do this:
Going after the youngest friend
And if there were a couple of them and I wanted to go after the newest, add the
-n
switch back into the mix:You can also use regular expressions when enlisting the
-f
switch, so these would work, for example:Displaying their names
You can double check the processes names using the
-l
switch:Controlling the output
Or tell
pgrep
to list the process IDs delimited using a comma (,
):You can do cool things like this:
So how do I kill the high CPU process?
I would use the above to be more selective in going after a high CPU process. You could use the approach of killing using these methods:
Look at their CPU loads:
Here I've changed the delimiter from a comma (
,
) aka. this switch-d,
, to a pipe (|
) aka. this switch-d\|
, so that I can use it in agrep
. Doing this will return the process IDs like this:We then insert these into the
grep -E ...
command so we can filter the output fromtop
based on certain process IDs.This might seem like a lot of bending backwards, but we now know with certainty that the process IDs we're using are only the ones related to a give process named "weird.*friend".
From here you can find the process with the highest CPU and kill it, if you really want to go that way.
A more targeted approach to high CPU
The above shows the sorted output from
top
by the CPU column (14th). It's sorted from lowest to highest, so we take the last line (tail -1
) which would be the highest CPU process of the "weird.*friend" processes.