Linux 使程序在后台长久运行


想要程序在后台长久运行有多种方法:

1、使用 nohup + & 的方法

nohup 使用方法如下:

nohup COMMAND > stdout.log 2> stderr.log &

上述命令,会把程序的标准输出写入 stdout.log 文件;错误输出写入 stderr.log 文件

或者

nohup COMMAND > stdout.log 2>&1 &

上述命令,会把标准输出和错误输出全都写入 stdout.log 文件。

关于nohup:

gnu官方文档(GNU Coreutils 9.1)nohup命令说明如下:

nohupruns the given command with hangup signals ignored, so that the command can continue running in the background after you log out.

也就是说使用nohup 启动的命令会忽略 hangup 信号,所以当退出登录时,该命令会在后台继续运行。

既然说明里提到了hangup 信号(hangup signals),我们就来看看什么是hangup信号。使用kill -l命令可以看到系统里所有的信号:

$ kill -l
 1) SIGHUP	 2) SIGINT	 3) SIGQUIT	 4) SIGILL	 5) SIGTRAP
 6) SIGABRT	 7) SIGBUS	 8) SIGFPE	 9) SIGKILL	10) SIGUSR1

其中,SIGHUP就是上文提到的hangup 信号,编号为1。

使用man 7 signal 命令,可以看到关于信号较为详细的说明,其中关于SIGHUP的说明如下:

Signal     Value     Action   Comment
       ──────────────────────────────────────────────────────────────────────
       SIGHUP        1       Term    Hangup detected on controlling terminal
                                     or death of controlling process

根据说明,当控制终端挂断(也就是断开)或控制进程死亡时,会发出SIGHUP信号,收到该信号的进程的默认行为(action)是 TermTerm 行为的描述如下:

Term   Default action is to terminate the process.

综上所述,当终端退出时,会发出SIGHUP信号,接收到该信号的进程的默认行为就是中止进程。那么,会给哪些进程发送信号呢?GNU文档Termination-Signals对此有如下说明:

Macro: int SIGHUP
This signal is also used to report the termination of the controlling process on a 
terminal to jobs associated with that session; this termination effectively disconnects
 all processes in the session from the controlling terminal.

翻译过来就是,当一个终端的控制进程中止时,会报告给同一session 下关联的的所有job

当我们使用终端登录时,系统自动为我们分配一个session,从该终端启动的所有进程及其子进程,都隶属于同一个session,该session下的所有进程称为一个session组;当用户退出登录时,该session组下的进程将会收到SIGHUP信号。

综上所述,当终端退出时,该session下的所有进程收到 SIGHUP信号,该信号的默认行为是中止进程;而使用nohup启动的进程,会忽略该信号

2、使用 tmux

tmux 用起来还是比较复杂,下载及使用可以参考官方地址:

https://github.com/tmux/tmux/wiki

3、使用 screen

screen 与 tmux 类似,可参考这里:

Screen - GNU Project - Free Software Foundation


文章作者: sfc9982
版权声明: 本博客所有文章除特別声明外,均采用 CC BY-NC-ND 4.0 许可协议。转载请注明来源 sfc9982 !
  目录