如果我打开一个终端并运行以下脚本,它工作正常。调用中的值gdbus
被写入lockScreenTest.txt
文件。屏幕锁定时值为 true,屏幕解锁时值为 false。
#!/bin/bash
while true; do
echo "$(gdbus call -e -d com.canonical.Unity -o /com/canonical/Unity/Session -m com.canonical.Unity.Session.IsLocked)" >> lockScreenTest.txt
sleep 2
echo "called" >> lockScreenTest.txt
done
但是,如果我将此行添加./lockScreenCheck.sh&
到~/.profile
并重新启动计算机,则输出gdbus
不会写入lockScreenTest.txt
. 相反,仅写入以下输出:
called
called
called
called
called
called
called
called
called
called
called
called
called
called
called
called
called
called
called
called
called
called
called
called
called
called
called
called
called
called
called
called
called
called
called
called
called
called
called
called
gdbus
为什么从 运行脚本时输出不可用~/.profile
?
我正在对此进行调查,因为我编写了一个 Java 程序,该程序需要检查屏幕是否被锁定,并且我正在使用大致以下命令进行操作:
String command = "gdbus call -e -d com.canonical.Unity -o /com/canonical/Unity/Session -m com.canonical.Unity.Session.IsLocked";
p = Runtime.getRuntime().exec(command);
p.waitFor();
与 bash 脚本一样,如果我从带有 的终端运行 Java 程序,它也可以正常工作java -jar program.jar
,但如果我从 调用它~/.profile
,Java 程序会运行,但 gdbus 命令的输出是难以捉摸的。
它可能会失败,因为
gdbus
无法建立与正在运行的会话总线的连接。请记住,这
~/.profile
是由登录 shell 提供的;显示管理器可能会在登录 shell 中调用用户的桌面会话,但您不应该指望它,即使它确实如此,会话也将是 shell 的子进程,而不是相反 - 环境诸如DBUS_SESSION_BUS_ADDRESS
不会在父 shell 中设置的变量。对于需要连接到桌面会话总线的应用程序,您最好使用 GUI 的“启动应用程序”功能 - 例如,请参阅如何在登录时自动启动应用程序?