在 Linux 中,nohup
命令用于在后台运行程序,即使关闭终端或断开连接,程序也会继续运行。要实现自动重启,可以结合 nohup
和其他工具,如 while
循环或 systemd
服务。
方法一:使用 while 循环
创建一个 shell 脚本(例如 run.sh
),内容如下:
#!/bin/bash
while true; do
nohup your_command &
wait $!
echo "Restarting your_command after failure..."
sleep 5
done
将 your_command
替换为你要运行的命令。然后,给予脚本执行权限并运行:
chmod +x run.sh
./run.sh
这将使 your_command
在后台运行,并在发生故障时自动重启。
方法二:使用 systemd 服务
创建一个 systemd 服务文件(例如 /etc/systemd/system/your_service.service
),内容如下:
[Unit]
Description=Your Service Description
[Service]
ExecStart=/path/to/your_command
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
将 /path/to/your_command
替换为你要运行的命令的路径。然后,执行以下命令启用并启动服务:
sudo systemctl enable your_service.service
sudo systemctl start your_service.service
这将使 your_command
作为 systemd 服务运行,并在发生故障时自动重启。