透過自己寫 Systemd Unit Files 方式來取代傳統的 (crontab) cron table 來啟動程式,執行一段時間卻發生程式莫名死掉了.
main process exited, code=killed, status=9/KILL
下面使用的 systemd 設定檔可以避免這個問題.
測試環境 CentOS 8 x86_64 (虛擬機)
程式如下.寫了一支會定期 60 秒寫入時間資料到檔案的 c++ 程式.
[root@localhost ~]# vi test.cpp #include <fstream> #include <iostream> #include <chrono> #include <ctime> #include <unistd.h> using namespace std; int main() { while(true) { ofstream myFile_Handler; // File Open myFile_Handler.open("/tmp/1.txt", std::ios_base::app); auto timenow = chrono::system_clock::to_time_t(chrono::system_clock::now()); // Write to the file myFile_Handler << ctime(&timenow) << endl; // File Close myFile_Handler.close(); // Sleep sleep(60); } }
編譯成可執行檔.
[root@localhost ~]# g++ test.cpp -o test
程式放到 /sbin/ 路徑.
[root@localhost ~]# cp test /sbin/
開始編輯 Systemd Unit Files (一般使用者寫的 service 檔案放在 /etc/systemd/system/ ,系統的放在 /usr/lib/systemd/system).
[root@localhost ~]# vi /etc/systemd/system/test.service [Unit] Description=Test Job [Service] Type=simple ExecStart=/sbin/test Restart=always RestartSec=5s [Install] WantedBy=multi-user.target
只簡單設定3個區塊
- [unit]
Description=Test Job
Description 敘述該 Systemd Unit Files 目的.
- [Service]
Type=simple ExecStart=/sbin/test
Type=simple – A long-running process that does not background its self and stays attached to the shell.
ExecStart – 指定執行程式.這邊會確保當程式死掉後 5 秒後會自動啟動.
Restart=always
RestartSec=5s - [Install]
WantedBy=multi-user.target
指定哪一個 runlevel 執行.
啟動服務
[root@localhost ~]# systemctl enable test.service Created symlink /etc/systemd/system/multi-user.target.wants/test.service → /etc/systemd/system/test.service. [root@localhost ~]# systemctl start test.service [root@localhost ~]# systemctl status test.service ● test.service - Test Job Loaded: loaded (/etc/systemd/system/test.service; enabled; vendor preset: disabled) Active: active (running) since Fri 2022-11-25 11:02:40 CST; 7s ago Main PID: 89850 (test) Tasks: 1 (limit: 49322) Memory: 292.0K CGroup: /system.slice/test.service └─89850 /sbin/test Nov 25 11:02:40 localhost.localdomain systemd[1]: Started Test Job.
檢視 /sbin/test (定期 60 秒寫入時間資料到檔案 /tmp/1.txt) 是否有正常執行.
[root@localhost ~]# cat /tmp/1.txt Fri Nov 25 11:02:40 2022 Fri Nov 25 11:03:40 2022 Fri Nov 25 11:04:40 2022
測試一下程式自動 restart 功能.手動把程式刪除.
[root@localhost ~]# ps -aux | grep -i test root 64661 0.0 0.0 13780 1824 ? Ss 10:51 0:00 /sbin/test root 64663 0.0 0.0 12136 1108 pts/0 R+ 10:51 0:00 grep --color=auto -i test [root@localhost ~]# kill 64661 [root@localhost ~]# ps -aux | grep -i test root 64669 0.0 0.0 12136 1144 pts/0 S+ 10:51 0:00 grep --color=auto -i test
等待 5 秒後再檢查一下程式是否自動啟動,程式已自動啟動.
[root@localhost ~]# ps -aux | grep -i test root 64672 0.0 0.0 13780 1948 ? Ss 10:51 0:00 /sbin/test root 64674 0.0 0.0 12136 1096 pts/0 S+ 10:51 0:00 grep --color=auto -i test
沒有解決問題,試試搜尋本站其他內容