gpt4 book ai didi

ubuntu - 如何从 systemd 用户服务访问 session D-Bus?

转载 作者:行者123 更新时间:2023-12-04 19:15:36 26 4
gpt4 key购买 nike

我有运行 shell 脚本的用户服务,它试图访问我的 session 的锁屏状态,如下所示:

# 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
}

问题是服务“是每个用户的进程,而不是每个 session ”,我不知道如何访问 session 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 [ "$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

如评论中所述,您需要以两种方式调用此脚本。当您的用户登录时,以服务模式启动此脚本。我使用“启动应用程序”程序来调用脚本,但它的调用方式并不重要,只要它在登录时由您的用户帐户调用即可。
然后从您的用户服务中,只需调用此脚本,如果屏幕被锁定,它将返回“true”,如果屏幕解锁,它将返回“false”。

关于ubuntu - 如何从 systemd 用户服务访问 session D-Bus?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38623791/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com