OS X’s Fast User Switching makes it easy for multiple users to share one Mac. But it does have one flaw: If several users log in but then don’t log out, you can end up with all of those accounts running in the background, sucking up system resources. But MacOSXHints.com reader Sesquipedalian figured out a way to automatically log out those idle users:
To keep the benefits of Fast User Switching while avoiding the situation in which multiple users remain logged in unnecessarily, you need a way to automatically log out users whose accounts have been running in the background for a specific period of time. Unfortunately, Mac OS X does not provide a way to do this. (There is a setting in the Security preference pane for logging out automatically after a certain amount of idle time, but that logs out all users and only does so when no one uses the computer for the specified period of time; as long as someone is using the computer, all background users stay logged in.)
My solution is to create a launch agent:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<string>if [ $(stat -f %u /dev/console) == $UID ]; then if [ -e /tmp/backgroundUserLogout.$UID ]; then rm /tmp/backgroundUserLogout.$UID; fi; elif [ ! -e /tmp/backgroundUserLogout.$UID ]; then touch /tmp/backgroundUserLogout.$UID; elif [ $(( <code>date +%s</code> - <code>stat -f %m /tmp/backgroundUserLogout.$UID || printf 0</code> )) -ge $(( 60 * 30 )) ]; then rm /tmp/backgroundUserLogout.$UID; osascript -e ‘tell application “System Events” to log out’; fi</string>
Save this code in a file named com.username.backgroundUserLogout.plist in the LaunchAgents folder of each user’s Library folder
This launch agent first checks to see whether the user has control of the OS X console (i.e., the GUI). If not, it then keeps track of how long that is the case. Once the user has been in the background for 30 minutes, the launch agent will automatically send the signal to log the user out. If the user has unsaved documents, the log out will be aborted.
You can adjust that idle time by replacing
30 in the string
$(( 60 * 30 )) with however many minutes you want. If there are users who should never be automatically logged out (for example, an account that serves up a shared iTunes library), just don’t create the launch agent in their Library.
You can replace
username in the file name and the sixth line of the launch agent itself with whatever you want; just be sure they match. You’ll obviously need to create that LaunchAgents folder if it doesn’t already exist. And to avoid permissions problems, you may need to create the folder and .plist file while logged in to each user account. Finally, note that you can accomplish much the same thing with the utility ScriptSaver.