10.3: Control CPU usage while using fast user switching

Jan 21, '04 09:41:00AM

Contributed by: Anonymous

This is a follow-up to an earlier hint regarding fast user switching and scheduling priority/cpu usage. One commenter suggested renicing user processes as part of login or logout script, but I prefer to run the following script as a cron job, for a couple of reasons. First, I can run the cron job as root (which renice requires to increase priority) without having SetUID programs lying around. Second, a periodic cron job catches at & batch jobs, periodic jobs, processes started via ssh, and other processes that are started by other users after logout or login.
B The downside to this approach, of course, is that there is a certain variable lag time between login/user switching and a user's processes being reniced. The truly harried or impatient may want to run the script via sudo on login.

Save the following script someplace logical; I use /usr/sbin/ or /var/root/bin/.


#!/bin/sh
#
# switch_nice
#
# renice processes so that the user at the main login window gets priority
#
 
# Determine who is logged in at the main terminal
#
# The user currently logged on at the main main termainal will be returned
# as the final argument to the only instance of login running on std
TOPUSER=`ps -auxww | grep login | grep std | grep -v grep | awk '{print $13}'`

# Determine what other processes have been given priority by admins
# and ought to be exempt -- THE FOLLOWING SHOULD BE ONE LONG LINE WITH A
# SINGLE SPACE REPLACING THE LINE BREAK!
EXEMPTIONS=(`ps -auxo nice | awk '{print $1, $2, $11}' | grep -v root |
 grep -v nobody | grep -e - | awk '{print $2}'`)

# Get names of users to be reniced -- THE FOLLOWING SHOULD BE ONE LONG
# LINE WITH A SINGLE SPACE REPLACING THE LINE BREAK!
SWITCHEDUSER=(`ps -auxww | grep -v $TOPUSER | grep -v root | grep -v nobody |
 awk '{print $1, $2}' | grep -v USER | awk '{print $1}' | sort -u`)

# Renice: others to 15, main terminal to 0, priority processes to -15
echo ${SWITCHEDUSER[*]} | xargs renice 15 -u
renice 0 -u $TOPUSER
echo ${EXEMPTIONS[*]} | xargs renice -15 -p

# Add additional rules...I renice my seti@home instances to 20
Then chmod u+x and add the following to your /etc/crontab:
*/5   *     *     *     *     root    </path/to/switch_nice>
Now every five minutes the system will check for processes run by other users and renice them.

Comments (6)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20040108113742335