nohup 命令可以让进程在用户退出登录后继续运行,但它本身并不提供自动重启功能。如果你想要实现进程的自动重启,可以考虑以下几种方法:
nohup 结合 & 和 sleep你可以编写一个简单的脚本来使用 nohup 启动进程,并在进程退出后使用 sleep 命令等待一段时间再重新启动。
#!/bin/bash
while true; do
    nohup your_command &
    wait $!
    echo "Process exited with code $?; restarting in 5 seconds..."
    sleep 5
done
将 your_command 替换为你想要运行的命令。
systemd 服务如果你使用的是 Linux 系统,并且 systemd 是系统初始化系统,你可以创建一个 systemd 服务来实现进程的自动重启。
sudo nano /etc/systemd/system/your_service.service
[Unit]
Description=Your Service Description
After=network.target
[Service]
ExecStart=/path/to/your_command
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
将 /path/to/your_command 替换为你想要运行的命令的路径。
systemd 配置:sudo systemctl daemon-reload
sudo systemctl start your_service
sudo systemctl enable your_service
supervisordsupervisord 是一个进程控制系统,可以用来管理和监控进程。
supervisord:sudo apt-get install supervisor
sudo nano /etc/supervisor/conf.d/your_service.conf
[program:your_service]
command=/path/to/your_command
autostart=true
autorestart=true
stderr_logfile=/var/log/your_service.err.log
stdout_logfile=/var/log/your_service.out.log
将 /path/to/your_command 替换为你想要运行的命令的路径。
supervisord 配置并启动服务:sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start your_service
cron 定时任务你可以使用 cron 来定期检查进程是否在运行,并在进程退出时重新启动它。
cron 任务:crontab -e
* * * * * pgrep -f your_command || /path/to/your_restart_script.sh
将 /path/to/your_restart_script.sh 替换为你之前编写的重启脚本的路径。
通过这些方法,你可以实现进程的自动重启。选择哪种方法取决于你的具体需求和系统环境。