I'm guessing the problem you want to solve is that you have some process running on your box which sometimes misbehaves, and sits forever pegging a core.
The first thing you want to do is to attempt to fix the program that goes crazy. That is by far the best solution. I'm going to assume that isn't possible, or you need a quick kluge to keep your box running until its fixed.
You, at minimum, want to limit your script to only hit the one program you're concerned about. It'd be best if permissions limited your script like this (e.g., your script runs as user X, the only other thing running as X is the program).
Even better would be to use something like ulimit -t
to limit the amount of total CPU time that the program can use. Similarly, if it consumes all memory, check ulimit -v
. The kernel enforces these limits; see the bash
manpage (it's a shell built-in) and the setrlimit(2)
manpage for details.
If the problem isn't a process running amok, but is instead just too many processes running, then implement some form of locking to prevent more than X from running (or—this should be getting familiar—ulimit -u
). You may also consider changing the scheduler priority of those processes (using nice
or renice
), or for even more drastic, using sched_setscheduler
to change the policy to SCHED_IDLE
.
If you need even more control, take a look a control groups (cgroups). Depending on the kernel you're running, you can actually limit the amount of CPU time, memory, I/O, etc. that a whole group of processes together consume. Control groups are quite flexible; they can likely do whatever you're trying to do, without any fragile kluges. The Arch Linux Wiki has an intro to cgroups that's worth reading, as is Neil Brown's cgroups series at LWN.
while [ 1 ]
makes me wonder how much CPU this script alone is going to consume. Also, 3 calls tokill -9
in a script running constantly? This gives me the chills ...sleep 1
in the loop