centos

如何用nohup在CentOS上保持进程运行

小樊
40
2025-03-29 21:22:20
栏目: 智能运维

在 CentOS 上,nohup 命令用于在后台运行程序,即使关闭终端或断开连接,程序也会继续运行

  1. 打开终端。

  2. 使用 nohup 命令运行程序。基本语法如下:

nohup command-to-run &

其中,command-to-run 是要运行的命令,& 表示将命令放入后台运行。

例如,如果你想在后台运行名为 my_script.sh 的脚本,可以使用以下命令:

nohup ./my_script.sh &
  1. 运行命令后,你会看到类似以下的输出:
nohup: ignoring input and appending output to 'nohup.out'

这意味着程序的输出已被重定向到名为 nohup.out 的文件中。你可以使用 tail 命令查看输出:

tail -f nohup.out
  1. 若要在后台运行程序并指定输出文件,可以使用以下命令:
nohup command-to-run > output-file 2>&1 &

例如:

nohup ./my_script.sh > my_output.out 2>&1 &

这将把标准输出和错误输出都重定向到 my_output.out 文件中。

  1. 若要在后台运行程序并禁用输出,可以将输出重定向到 /dev/null
nohup command-to-run > /dev/null 2>&1 &

这样,程序的输出将被丢弃,不会生成 nohup.out 文件。

现在,即使关闭终端或断开连接,程序也会在后台继续运行。 若要检查程序是否仍在运行,可以使用 ps 命令:

ps aux | grep command-to-run

command-to-run 替换为你要查找的命令。

0
看了该问题的人还看了