linux

nohup命令如何在Linux中实现任务的自动重启

小樊
44
2025-10-17 23:39:24
栏目: 智能运维

nohup(no hang-up)命令在 Linux 中用于在后台运行程序,即使关闭终端或断开连接,程序也会继续运行

  1. 使用 nohup 命令启动程序:

    nohup your_command &
    

    这将在后台运行 your_command,并将输出重定向到名为 nohup.out 的文件。

  2. 创建一个 shell 脚本,例如 run_my_command.sh,并在其中添加以下内容:

    #!/bin/bash
    while true; do
        nohup your_command > /dev/null 2>&1 &
        wait $!
        echo "Restarting your_command in 5 seconds..."
        sleep 5
    done
    

    这个脚本将无限循环地运行 your_command,并在每次执行完成后等待 5 秒钟。> /dev/null 2>&1 将输出重定向到 /dev/null,这样你就不会看到任何输出。

  3. 为脚本添加可执行权限:

    chmod +x run_my_command.sh
    
  4. 使用 nohup 命令运行脚本:

    nohup ./run_my_command.sh &
    

    这将在后台运行 run_my_command.sh,即使关闭终端或断开连接,程序也会继续运行并自动重启 your_command

请注意,这种方法仅适用于简单的用例。对于更复杂的任务管理和监控,你可能需要考虑使用进程管理器(如 systemdsupervisordpm2)。

0
看了该问题的人还看了