How to properly end a KDE session from shell without root privileges

You can send a logout command via dbus to KDE, which should (if it can) terminate the session.

qdbus org.kde.ksmserver /KSMServer logout 0 0 0

dbus is a messaging system that lets applications communicate with each other, and the qdbus command is a utility for sending dbus messages to applications.

Applications register with dbus, and the ksmserver part of KDE is the session manager - it looks after who is logged in.

So we are sending a message to ksmserver to the /KSMServer interface and telling it to logout. The message we are sending is the exact same message that is sent to KSM when you click on the logout icon on your desktop.

The three zeros are parameters and can alter the type of logout we are doing:

First parameter:

  • 0 = Do not wait for confirmation
  • 1 = Wait for confirmation (with a 30 second timeout)

Second parameter:

  • -1 = Prompt for action, defaulting to shutdown (Only makes sense when waiting for confirmation.)
  • 0 = Logout
  • 1 = Restart
  • 2 = Shutdown

The third parameter is the "when" parameter, but it isn't clear what its impact is.


The accepted answer is a solution specific for KDE5, a more generic approach would be

loginctl list-sessions
loginctl terminate-session <id>

or

loginctl terminate-user <username>

Source

There are more possible commands:

Session Commands:
  list-sessions            List sessions
  session-status [ID...]   Show session status
  show-session [ID...]     Show properties of sessions or the manager
  activate [ID]            Activate a session
  lock-session [ID...]     Screen lock one or more sessions
  unlock-session [ID...]   Screen unlock one or more sessions
  lock-sessions            Screen lock all current sessions
  unlock-sessions          Screen unlock all current sessions
  terminate-session ID...  Terminate one or more sessions
  kill-session ID...       Send signal to processes of a session

User Commands:
  list-users               List users
  user-status [USER...]    Show user status
  show-user [USER...]      Show properties of users or the manager
  enable-linger [USER...]  Enable linger state of one or more users
  disable-linger [USER...] Disable linger state of one or more users
  terminate-user USER...   Terminate all sessions of one or more users
  kill-user USER...        Send signal to processes of a user

Seat Commands:
  list-seats               List seats
  seat-status [NAME...]    Show seat status
  show-seat [NAME...]      Show properties of seats or the manager
  attach NAME DEVICE...    Attach one or more devices to a seat
  flush-devices            Flush all device associations
  terminate-seat NAME...   Terminate all sessions on one or more seats