在Ubuntu系统中,可以使用systemd或supervisord等工具来实现进程的自动重启。以下是使用这两种方法的简要说明:
方法1:使用systemd
/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/executable
Restart=always
RestartSec=3
[Install]
WantedBy=multi-user.target
这里,Description
是服务的描述,User
是运行服务的用户,WorkingDirectory
是工作目录,ExecStart
是要运行的可执行文件的路径。Restart=always
表示无论退出状态如何,服务都会自动重启。RestartSec=3
表示在重启之前等待3秒。
sudo systemctl daemon-reload
sudo systemctl start my_service
sudo systemctl enable my_service
现在,你的进程将在系统启动时自动运行,并在意外停止时自动重启。
方法2:使用supervisord
sudo apt-get update
sudo apt-get install supervisor
/etc/supervisor/conf.d/my_service.conf
。将以下内容粘贴到文件中,根据需要进行修改:[program:my_service]
command=/path/to/your/executable
directory=/path/to/working/directory
user=my_user
autostart=true
autorestart=true
stderr_logfile=/var/log/my_service.err.log
stdout_logfile=/var/log/my_service.out.log
这里,command
是要运行的可执行文件的路径,directory
是工作目录,user
是运行服务的用户。autostart=true
表示supervisord启动时自动启动该服务,autorestart=true
表示服务意外停止时自动重启。
sudo supervisorctl reread
sudo supervisorctl update
现在,你的进程将在supervisord启动时自动运行,并在意外停止时自动重启。你可以使用sudo supervisorctl status my_service
命令查看服务状态。