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

时间:2016-07-27 21:51:40

标签: ubuntu dbus systemd

我有运行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

1 个答案:

答案 0 :(得分:1)

我遇到了同样的问题,我的研究结果都没有。如果有人能找到更好的方式来查询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 [ "$1" == "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

如评论中所述,您需要以两种方式调用此脚本。用户登录时,请在服务模式下启动此脚本。我使用&#34;启动应用程序&#34;程序调用脚本,但只要在登录时由您的用户帐户调用它,它的调用方式并不重要。 然后从您的用户服务中,只需调用此脚本,它将返回&#34; true&#34;如果屏幕被锁定或“错误”#34;如果屏幕未锁定。