在 CentOS 系统中,你可以使用 nohup
命令结合 &
符号将命令放入后台运行,并使用 while
循环来实现命令的自动重启。以下是一个示例:
打开终端。
输入以下命令:
nohup your_command &
# 用实际需要运行的命令替换 "your_command"
这将在后台运行你的命令,并将输出重定向到名为 nohup.out
的文件。
while
循环。在终端中输入以下命令:while true; do nohup your_command &; wait $!; echo "Command restarted due to failure"; done
# 用实际需要运行的命令替换 "your_command"
这将使得 your_command
在后台运行,如果命令失败(返回非零退出状态),则循环将捕获错误并输出 “Command restarted due to failure”。然后,循环将重新启动命令。
Ctrl + C
终止循环。请注意,这种方法仅适用于简单的自动重启需求。对于更复杂的场景,你可能需要考虑使用进程管理工具,如 systemd
或 supervisord
。