将 Redshift 脚本作为服务运行

将 Redshift 脚本作为服务运行

我对 Linux 还很陌生,我正在尝试练习编写脚本和制作自己的服务。我想将我的简单红移脚本(用于更改屏幕色温)变成一项服务。当我在终端中执行该脚本时,该脚本可以正常工作,但当我尝试在 .service 文件中执行它时,我遇到了问题。任何帮助都将不胜感激。

我的脚本(redshift.sh):

#!/bin/bash
redshift -O 1500

通过运行,./redshift.sh我看到我的屏幕改变色温并得到输出:Using method randr

我的服务(redshift.service):

[Unit]
Description=Set Redshift
[Service]
Type=simple
ExecStart=/bin/bash /usr/bin/redshift.sh
[Install]
WantedBy=default.target

期望是redshift.服务执行我的脚本redshift.sh

设置服务:

我将脚本文件复制到/usr/bin并将模式更改为 x(可执行)。

sudo cp redshift.sh /usr/bin/redshift.sh 
sudo chmod +x /usr/bin/redshift.sh

我将服务文件复制到/etc/systemd/system并将模式更改为 644。

sudo cp redshift.service /etc/systemd/system/redshift.service 
sudo chmod 644 /etc/systemd/system/redshift.service 

尝试运行我的服务:

sudo systemctl start redshift

显示色温不变!

获取服务状态:

sudo systemctl status redshift

根据 systemctl status 的输出判断,我发现该脚本尝试执行,但发生了一些失败。您知道为什么会出现这种情况吗?状态输出如下所示。

"Loaded: loaded (/etc/systemd/system/redshift.service; disabled; vendor preset: enabled)
     Active: failed (Result: exit-code) since Fri 2020-09-04 11:40:11 EDT; 8s ago
    Process: 21928 ExecStart=/bin/bash /usr/bin/redshift.sh (code=exited, status=1/FAILURE)
   Main PID: 21928 (code=exited, status=1/FAILURE)

Sep 04 11:40:11 labpc-ThinkPad-T540p bash[21933]: `RANDR Query Version' returned error -1
Sep 04 11:40:11 labpc-ThinkPad-T540p bash[21933]: Initialization of randr failed.
Sep 04 11:40:11 labpc-ThinkPad-T540p bash[21933]: Trying next method...
Sep 04 11:40:11 labpc-ThinkPad-T540p bash[21933]: No protocol specified
Sep 04 11:40:11 labpc-ThinkPad-T540p bash[21933]: X request failed: XOpenDisplay
Sep 04 11:40:11 labpc-ThinkPad-T540p bash[21933]: Initialization of vidmode failed.
Sep 04 11:40:11 labpc-ThinkPad-T540p bash[21933]: Trying next method...
Sep 04 11:40:11 labpc-ThinkPad-T540p bash[21933]: No more methods to try.
Sep 04 11:40:11 labpc-ThinkPad-T540p systemd[1]: redshift.service: Main process exited, code=exited, status=1/FA>
Sep 04 11:40:11 labpc-ThinkPad-T540p systemd[1]: redshift.service: Failed with result 'exit-code'."

状态输出

我按照本教程来提供我的服务:https://www.linode.com/docs/quick-answers/linux/start-service-at-boot/#create-a-custom-systemd-service

答案1

您可能必须设置环境变量,例如 display 和 Xauth。

我的服务已将此行添加到[service]部分

Environment="DISPLAY=:0" "XAUTHORITY=/run/user/1000/gdm/Xauthority"

看到这个线了解更多详情。

此外,execstart 不必是 .sh。您可以将路径设置为 redshift exec(或者在您的情况下,像在终端中一样键入命令,因为我猜 redshift 在您的 PATH 中)

答案2

您需要将显示定义为环境并在显示管理器启动后运行。

请参阅下面的内容。

[Unit]
Description=Redshift
After=display-manager.service

[Service]
Environment=DISPLAY=:0
ExecStart=/usr/bin/redshift -O 1500
Restart=always

[Install]
WantedBy=default.target

您还可以定义参数ExeStart并消除额外的自定义 bash 脚本。

相关内容