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?
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).
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
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
You can also use regular expressions when enlisting the
Displaying their names
You can double check the processes names using the
Controlling the output
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 (
We then insert these into the
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
@msw, @sim and other users have raised valid concerns as to the concept of my script. Inspired by @sim's answer and msw's remarks I have sat down and rethought how to solve my particular issue (couple of known processes causing trouble now and then). Here is what I came up with:
In contrast to the previous script this one will only kill the process with the highest CPU load if its name matches a number of known troublemakers (processes that tend to lock up on your system).
Here's a simple script that will determine the process causing the highest momentary CPU load on the system and kill it (with the exception of Xorg, which would cause the GUI to crash):