centos

CentOS nohup如何实现命令自动重启

小樊
46
2025-07-22 23:08:34
栏目: 智能运维

在 CentOS 系统中,nohup 命令可以让你的程序在后台运行,即使关闭终端或者断开连接也不会中断

  1. 使用 nohup& 将程序放入后台运行:
nohup your_command &

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

  1. 使用 systemd 创建一个服务单元文件:

首先,创建一个新的服务单元文件,例如 /etc/systemd/system/your_service.service,并使用以下内容填充它(确保替换 your_command 为实际命令):

[Unit]
Description=Your custom service
After=network.target

[Service]
Type=simple
ExecStart=/path/to/your_command
Restart=always
User=your_user
Group=your_group

[Install]
WantedBy=multi-user.target

这个配置文件定义了一个名为 your_service 的服务,它将在网络启动后自动运行。ExecStart 指定了要运行的命令,Restart=always 表示无论程序退出状态如何,都会自动重启。

  1. 重新加载 systemd 配置:
sudo systemctl daemon-reload
  1. 启动新创建的服务:
sudo systemctl start your_service
  1. 设置服务开机自启:
sudo systemctl enable your_service

现在,你的命令将在系统启动时自动运行,并在意外停止时自动重启。你可以使用以下命令查看服务状态:

sudo systemctl status your_service

0
看了该问题的人还看了