如何从 systemd 用户服务访问会话 D-Bus?

How to access session D-Bus from systemd user service?

我有用户服务 运行 shell 脚本,它正试图像这样访问我的会话的锁屏状态:

# Test Unity screen-lock:
isLocked() {
    isLocked=$(gdbus call -e -d com.canonical.Unity -o /com/canonical/Unity/Session -m com.canonical.Unity.Session.IsLocked)
}

lock() {
  if [[ $isLocked == "(false,)" ]]; then                                                                                                     
        gnome-screensaver-command -l
  elif [[ $isLocked == "(true,)" ]]; then                                                                                                
        exit 1
  fi
exit 0
}

问题是服务“是每个用户的进程,而不是每个会话”,我不知道如何访问会话 dbus:

GDBus.Error:org.freedesktop.DBus.Error.ServiceUnknown: The name com.canonical.Unity was not provided by any .service files

我也面临同样的问题,我的研究没有任何结果。如果有人能找到更好的方法来查询 Unity 的锁定状态,我很想听听。

我最近了解了命名管道,当时我想知道我可以用这样的东西做什么。事实证明,这个问题恰好是一个完美的应用。

创建以下脚本...

#!/bin/bash
# this script is meant to be called in two different ways.
# 1.    It can be called as a service by passing "service" as the first argument. In this 
#   mode, the script listens for requests for lock screen status. The script should be
#   run in this mode with startup applications on user logon.
# 2.    If this script is called without any arguments, it will call the service to request
#   the current lock screen status. Call this script in this manner from your user 
#   service.

# this will be the named pipe we'll use for requesting and receiving screen lock status
pipe="/tmp/lockscreen-status"

if [ "" == "service" ]; then
    # setup the named pipe
    rm "$pipe"
    mkfifo "$pipe"

    # start watching for requests
    while true
    do
        # watch the pipe for trigger events requesting lock screen status
        read request < "$pipe"

        # respond across the same pipe wit the current lock screen status
        gdbus call -e -d com.canonical.Unity -o /com/canonical/Unity/Session -m com.canonical.Unity.Session.IsLocked | grep -oP "(true)|(false)" > "$pipe"
    done
else
    # make sure the pipe exists
    if [ ! -e "$pipe" ]; then
        echo "This script must started in service mode before lock status can be queried."
        exit
    fi

    # send a request for screen lock status and read the response
    touch "$pipe"
    read status < "$pipe"

    [ "$status" == "" ] && status="This script must started in service mode before lock status can be queried."

    # print reponse to screen for use by calling application
    echo $status
fi

如评论中所述,您需要通过两种方式调用此脚本。当您的用户登录时,以服务模式启动此脚本。我使用 "Startup Applications" 程序来调用脚本,但只要您的用户帐户在登录时调用它,它的调用方式并不重要。 然后在您的用户服务中,只需调用此脚本,如果屏幕已锁定,它将 return "true",如果屏幕已解锁,它将 "false"。