nohup
(no hang-up)命令用于在后台运行程序,使其在用户退出登录后仍然继续运行。默认情况下,nohup
会忽略挂起(SIGHUP)信号,从而防止进程被系统终止。以下是一些使用nohup
的常见方法和注意事项:
nohup command &
command
是你想要在后台运行的命令。&
将命令放入后台运行。通常,nohup
会将命令的输出重定向到一个名为 nohup.out
的文件中,除非你指定了其他输出文件。
nohup command > output.log 2>&1 &
> output.log
将标准输出重定向到 output.log
文件。2>&1
将标准错误输出重定向到标准输出,即 output.log
文件。使用 disown
命令:
如果你已经启动了一个进程,可以使用 disown
命令将其从当前 shell 的作业表中移除,从而防止它被挂起信号终止。
nohup command &
disown
使用 screen
或 tmux
:
screen
和 tmux
是终端复用工具,可以在一个终端会话中创建多个独立的终端窗口,并且即使断开连接,这些窗口中的进程也会继续运行。
screen -S mysession
command
# 按 Ctrl+A 然后按 D 键分离会话
重新连接会话:
screen -r mysession
使用 systemd
服务:
对于需要长期运行的服务,可以创建一个 systemd
服务单元文件,使其作为系统服务运行。
[Unit]
Description=My Service
[Service]
ExecStart=/path/to/command
Restart=always
[Install]
WantedBy=multi-user.target
将文件保存为 /etc/systemd/system/myservice.service
,然后启用并启动服务:
sudo systemctl enable myservice
sudo systemctl start myservice
通过这些方法,你可以确保进程在用户退出登录或系统重启后仍然继续运行。