温馨提示×

nohup在CentOS中如何确保进程持续运行

小樊
51
2025-07-20 22:52:40
栏目: 智能运维

在CentOS中,nohup命令用于在后台运行程序,即使关闭终端或断开SSH连接,程序也会继续运行。要确保进程持续运行,请按照以下步骤操作:

  1. 打开终端。

  2. 使用nohup命令启动程序。例如,如果要运行名为my_script.sh的脚本,请输入以下命令:

nohup ./my_script.sh &

这里的&符号表示将程序放入后台运行。

  1. nohup命令会将程序的输出重定向到一个名为nohup.out的文件中。你可以使用以下命令查看输出:
tail -f nohup.out
  1. 如果你想将输出重定向到其他文件,可以使用以下命令:
nohup ./my_script.sh > output.log 2>&1 &

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

  1. 若要确保进程在系统重启后自动运行,可以使用systemd创建一个服务单元。首先,创建一个名为my_service.service的文件:
sudo vi /etc/systemd/system/my_service.service
  1. my_service.service文件中,添加以下内容:
[Unit]
Description=My custom service

[Service]
ExecStart=/path/to/your/script.sh
Restart=always
User=username
Group=groupname
Environment=PATH=/usr/bin:/usr/local/bin

[Install]
WantedBy=multi-user.target

/path/to/your/script.sh替换为你的脚本路径,usernamegroupname替换为运行脚本的用户和组。

  1. 保存并关闭文件。然后运行以下命令启用服务:
sudo systemctl enable my_service.service
  1. 若要启动服务,请运行:
sudo systemctl start my_service.service
  1. 若要检查服务状态,请运行:
sudo systemctl status my_service.service

现在,你的进程将在CentOS中持续运行,即使关闭终端或断开SSH连接。

0