在Ubuntu系統中,可以使用systemd服務來實現進程的自動重啟。以下是創建一個systemd服務并設置自動重啟的步驟:
/etc/systemd/system/my_service.service。將my_service替換為您的服務名稱。sudo nano /etc/systemd/system/my_service.service
[Unit]
Description=My custom service
After=network.target
[Service]
Type=simple
User=my_user
WorkingDirectory=/path/to/working/directory
ExecStart=/path/to/your/application --option1 --option2
Restart=always
RestartSec=3
[Install]
WantedBy=multi-user.target
將my_user替換為您要運行服務的用戶,將/path/to/working/directory替換為應用程序的工作目錄,將/path/to/your/application替換為應用程序的可執行文件路徑。--option1和--option2是傳遞給應用程序的參數,可以根據需要進行修改。
Restart=always表示無論退出狀態如何,始終重啟服務。RestartSec=3表示在重啟之前等待3秒。
保存并關閉服務文件。
重新加載systemd配置。運行以下命令,使systemd重新加載服務文件:
sudo systemctl daemon-reload
sudo systemctl start my_service
sudo systemctl enable my_service
現在,您的服務已經設置為自動重啟。如果服務意外停止,systemd將在指定的時間間隔后自動重啟它。