將 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

期望是擁有紅移服務執行我的腳本紅移.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

您可能必須設定環境變量,例如顯示和 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 腳本。

相關內容