Linux后台运行进程方法概述
本文汇总了在Linux系统中确保进程于后台稳定执行的多种技巧与策略。
日常运维中常遇此类状况:经由telnet或ssh连接至远程Linux主机,执行耗时较长的任务,却因网络连接波动致使任务中途夭折。如何确保指令发出后,即便本地终端关闭或网络断开,任务仍能持续进行?下文列举若干实例,供读者依据具体情境选用适宜的处理手段。
nohup/setsid/&
场景:
若仅需临时让某条命令在后台长时间运行,何种方式最为简便且能保障其稳定性?
解决方法:
通常情况下,用户注销(logout)或网络断开时,终端将接收HUP(hangup)信号,进而终止其所有子进程。因此,应对策略主要有两条路径:一是使进程忽略HUP信号,二是让进程运行于新的会话中,使其不再作为当前终端的子进程存在。
hangup 名称的来由
在Unix早期版本里,各终端均借由modem与系统进行通信。用户logout时,modem会挂断(hang up)电话;同理,modem断开连接时,亦会向终端发送hangup信号以通知其关闭所有子进程。
1. nohup
nohup无疑是首选方案。顾名思义,其功能在于令提交的命令忽略hangup信号。首先查阅nohup的帮助文档:
NOHUP(1) User Commands NOHUP(1)
NAME
nohup - run a command immune to hangups, with output to a non-tty
SYNOPSIS
nohup COMMAND [ARG]...
nohup OPTION
DESCRIPTION
Run COMMAND, ignoring hangup signals.
--help display this help and exit
--version
output version information and exit
从帮助信息可见,nohup的使用极为便捷,只需在处理命令前添加nohup即可。默认情况下,标准输出和标准错误将被重定向至nohup.out文件。通常建议在末尾加上"&"以将命令置于后台运行,亦可使用">filename 2>&1"来自定义重定向的目标文件名。
nohup 示例
[root@pvcent107 ~]# nohup ping www.ibm.com &
[1] 3059
nohup: appending output to `nohup.out'
[root@pvcent107 ~]# ps -ef |grep 3059
root 3059 984 0 21:06 pts/3 00:00:00 ping www.ibm.com
root 3067 984 0 21:06 pts/3 00:00:00 grep 3059
[root@pvcent107 ~]#
2、setsid
nohup通过忽略HUP信号防止进程中断。若转换思路,假设进程不属于接收HUP信号的终端的子进程,自然便不会受其影响。setsid工具可实现此目的。先查看setsid的帮助信息:
SETSID(8) Linux Programmer's Manual SETSID(8)
NAME
setsid - run a program in a new session
SYNOPSIS
setsid program [ arg ... ]
DESCRIPTION
setsid runs a program in a new session.
由帮助信息可知,setsid的使用同样简便,只需在待处理命令前加上setsid即可。
setsid 示例
[root@pvcent107 ~]# setsid ping www.ibm.com
[root@pvcent107 ~]# ps -ef |grep www.ibm.com
root 31094 1 0 07:28 ? 00:00:00 ping www.ibm.com
root 31102 29217 0 07:29 pts/4 00:00:00 grep www.ibm.com
[root@pvcent107 ~]#
值得注意的是,上述示例中进程ID(PID)为31094,而其父ID(PPID)为1(即init进程ID),并非当前终端的进程ID。请对比nohup示例中的父ID差异。
3、这里还有一个关于 subshell 的小技巧。我们知道,将一个或多个命名包含在“()”中就能让这些命令在子 shell 中运行中,从而扩展出很多有趣的功能,我们现在要讨论的就是其中之一。 当我们将"&"也放入“()”内之后,我们就会发现所提交的作业并不在作业列表中,也就是说,是无法通过jobs来查看的。让我们来看看为什么这样就能躲过 HUP 信号的影响吧。
subshell 示例
[root@pvcent107 ~]# (ping www.ibm.com &)
[root@pvcent107 ~]# ps -ef |grep www.ibm.com
root 16270 1 0 14:13 pts/4 00:00:00 ping www.ibm.com
root 16278 15362 0 14:13 pts/4 00:00:00 grep www.ibm.com
[root@pvcent107 ~]#
从示例可见,新提交进程的父ID(PPID)为1(init进程的PID),而非当前终端的进程ID。因此,该进程不属于当前终端的子进程,自然也不会受到当前终端HUP信号的影响。
disown
场景:
已知在命令前添加nohup或setsid可避免HUP信号影响。但若未加任何处理便已提交命令,该如何补救以规避HUP信号?
解决方法:
此时再添加nohup或setsid已无济于事,只能通过作业调度及disown命令来解决。查看disown的帮助信息:
disown [-ar] [-h] [jobspec ...]
Without options, each jobspec is removed from the table of
active jobs. If the -h option is given, each jobspec is not
removed from the table, but is marked so that SIGHUP is not
sent to the job if the shell receives a SIGHUP. If no jobspec
is present, and neither the -a nor the -r option is supplied,
the current job is used. If no jobspec is supplied, the -a
option means to remove or mark all jobs; the -r option without
a jobspec argument restricts operation to running jobs. The
return value is 0 unless a jobspec does not specify a valid
job.
由此可见,可采用以下方式达成目标。
使用disown -h jobspec使特定作业忽略HUP信号。
使用disown -ah使所有作业均忽略HUP信号。
使用disown -rh使正在运行的作业忽略HUP信号。
灵活运用 CTRL-z
日常工作中,可用CTRL-z将当前进程挂起并暂停于后台,执行其他操作后,再用fg将挂起的进程恢复至前台(或用bg将其置于后台)继续运行。这使得在一个终端内灵活切换多个任务成为可能,尤其在代码调试时极具价值。因为将代码编辑器挂起后再恢复,光标定位仍停留在上次挂起位置,省去了重新定位的麻烦。
需注意,使用disown后,目标作业将从作业列表中移除,无法再通过jobs命令查看,但仍可通过ps -ef查找。
然而存在一个问题:该方法的操作对象是作业。若在命令末尾添加"&"使其成为后台作业,则万事大吉,可通过jobs命令获取所有作业列表。但若未将当前命令作为作业运行,如何获取其作业号?答案便是使用CTRL-z(按住Ctrl键的同时按住z键)。
CTRL-z的作用是将当前进程挂起(Suspend),随后可用jobs命令查询其作业号,再用bg jobspec将其放入后台并继续运行。需注意的是,若挂起操作会影响当前进程的运行结果,请谨慎使用此方法。
disown 示例1(如果提交命令时已经用“&”将命令放入后台运行,则可以直接使用“disown”)
[root@pvcent107 build]# cp -r testLargeFile largeFile &
[1] 4825
[root@pvcent107 build]# jobs
[1]+ Running cp -i -r testLargeFile largeFile &
[root@pvcent107 build]# disown -h %1
[root@pvcent107 build]# ps -ef |grep largeFile
root 4825 968 1 09:46 pts/4 00:00:00 cp -i -r testLargeFile largeFile
root 4853 968 0 09:46 pts/4 00:00:00 grep largeFile
[root@pvcent107 build]# logout
disown 示例2(如果提交命令时未使用“&”将命令放入后台运行,可使用 CTRL-z 和“bg”将其放入后台,再使用“disown”)
[root@pvcent107 build]# cp -r testLargeFile largeFile2
[1]+ Stopped cp -i -r testLargeFile largeFile2
[root@pvcent107 build]# bg %1
[1]+ cp -i -r testLargeFile largeFile2 &
[root@pvcent107 build]# jobs
[1]+ Running cp -i -r testLargeFile largeFile2 &
[root@pvcent107 build]# disown -h %1
[root@pvcent107 build]# ps -ef |grep largeFile2
root 5790 5577 1 10:04 pts/3 00:00:00 cp -i -r testLargeFile largeFile2
root 5824 5577 0 10:05 pts/3 00:00:00 grep largeFile2
[root@pvcent107 build]#
screen
场景:
已掌握使进程免受HUP信号影响的方法,但若需在稳定后台中运行大量此类命令,如何避免对每条命令都进行单独操作?
解决方法:
此时最便捷的方法是screen。简言之,screen提供了ANSI/VT100终端模拟器,使其能在一个真实终端下运行多个全屏的伪终端。screen参数众多,功能强大,此处仅介绍常用功能并简要分析为何使用screen能避免HUP信号影响。先查看screen的帮助信息:
SCREEN(1) SCREEN(1)
NAME
screen - screen manager with VT100/ANSI terminal emulation
SYNOPSIS
screen [ -options ] [ cmd [ args ] ]
screen -r [[pid.]tty[.host]]
screen -r sessionowner/[[pid.]tty[.host]]
DESCRIPTION
Screen is a full-screen window manager that multiplexes a physical
terminal between several processes (typically interactive shells).
Each virtual terminal provides the functions of a DEC VT100 terminal
and, in addition, several control functions from the ISO 6429 (ECMA
48, ANSI X3.64) and ISO 2026 standards (e.g. insert/delete line and
support for multiple character sets). There is a scrollback history
buffer for each virtual terminal and a copy-and-paste mechanism that
allows moving text regions between windows.
使用screen十分方便,主要常用选项如下:
使用screen -dmS session name建立一个处于断开模式下的会话(并指定其会话名)。
使用screen -list列出所有会话。
使用screen -r session name重新连接指定会话。
使用快捷键CTRL-a d暂时断开当前会话。
screen 示例
[root@pvcent107 ~]# screen -dmS Urumchi
[root@pvcent107 ~]# screen -list
There is a screen on:
12842.Urumchi (Detached)
1 Socket in /tmp/screens/S-root.
[root@pvcent107 ~]# screen -r Urumchi
通过“-r”连接到screen会话后,便可在该伪终端中自由操作,无需担忧HUP信号影响进程,也不必给每个命令前添加“nohup”或“setsid”。原因何在?请看以下两个例子。
1. 未使用 screen 时新进程的进程树
[root@pvcent107 ~]# ping www.google.com &
[1] 9499
[root@pvcent107 ~]# pstree -H 9499
init─┬─Xvnc
├─acpid
├─atd
├─2*[sendmail]
├─sshd─┬─sshd───bash───pstree
│ └─sshd───bash───ping
可以看出,未使用screen时,所处的bash是sshd的子进程。当ssh断开连接时,HUP信号自然会影响到其下所有子进程(包括新建的ping进程)。
2. 使用了 screen 后新进程的进程树
[root@pvcent107 ~]# screen -r Urumchi
[root@pvcent107 ~]# ping www.ibm.com &
[1] 9488
[root@pvcent107 ~]# pstree -H 9488
init─┬─Xvnc
├─acpid
├─atd
├─screen───bash───ping
├─2*[sendmail]
而使用screen后情况不同,此时bash是screen的子进程,screen则是init(PID为1)的子进程。因此,当ssh断开连接时,HUP信号自然不会影响到screen下的子进程。
总结
上述几种方法已介绍完毕,可根据不同场景选择合适方案。nohup/setsid无疑是临时需求时最便捷的方法;disown能帮助事后补救已在运行的作业;而screen则是大批量操作时的不二之选。