Logout gracefully from KDE

For KDE 3.x, I use the command:
$ dcop --all-sessions --user username ksmserver default logout 0 0 0

For KDE 4.x, make sure the environment variable DBUS_SESSION_BUS_ADDRESS is set for the appropriate session. You can usually find this in /usr/home/username/.dbus/session-bus/. Then use the command:
$ qdbus org.kde.ksmserver /KSMServer org.kde.KSMServerInterface.logout 0 0 0