@WillireamAngel
2018-05-12T06:09:35.000000Z
字数 2900
阅读 1722
Linux
SSH远程登录Linux服务器,运行一些耗时较长的任务,为了防止网络不稳定等因素导致任务中途停止或防止进程占用终端,我们需要使用后台进程。(断开SSH时,终端会发送hangup信号,使其关闭所有子进程)
常见的管理后台进程的方法有nohup/setsid/&/screen/disown等。
用法:
[command] [> output flie] [2>&1] &
使用&可以直接使命令在后台运行,如果不添加> output flie 2>&1,所有输出都会在前台显示。
为了达到后台进程运行不受终端影响的目的,需要利用subshell对子进程进行操作:
([command] [> output flie] [2>&1] &)
此时,后台进程的父进程变成了init,无法用jobs查询到该进程,不再受终端控制。
subshell,子shell,shell脚本可以启动子进程,实现shell的并行执行。
格式:
(command1; command2; command3; ...)
subshell具有私有环境,变量私有,外部不可见。
更多subshell相关知识可参照:
http://tldp.org/LDP/abs/html/subshells.html
用法:
nohup option COMMAND [>filename] [2>&1]... &
nohup通过让提交的命令忽略hangup,实现后台进程不中断。
nohup man信息如下:
NOHUP(1) User Commands NOHUP(1)NAMEnohup - run a command immune to hangups, with output to a non-ttySYNOPSISnohup COMMAND [ARG]...nohup OPTIONDESCRIPTIONRun COMMAND, ignoring hangup signals.--help display this help and exit--versionoutput version information and exit
setid <command>
setsid通过将父进程切换为init,子进程不受hangup信息影响,其实现与(&)实现原理类似。
setsid man信息如下:
SETSID(1) User Commands SETSID(1)NAMEsetsid - run a program in a new sessionSYNOPSISsetsid program [arg...]DESCRIPTIONsetsid runs a program in a new session.OPTIONS-c, --cttySet the controlling terminal to the current one.
用法:
screen -dmS session name 建立一个处于断开模式下的会话(并指定其会话名)。screen -list 列出所有会话。screen -r session name 重新连接指定会话。快捷键CTRL-A d 来暂时断开当前会话。
screen是终端下的全屏伪终端,一个真实终端下可运行多个伪终端,用screen -r建立伪终端。使用screen,bash 是 screen 的子进程,而 screen 是 init的子进程。当 ssh 断开连接时,huangup信号不会影响到screen下面的子进程。
SCREEN(1) General Commands Manual SCREEN(1)NAMEscreen - screen manager with VT100/ANSI terminal emulationSYNOPSISscreen [ -options ] [ cmd [ args ] ]screen -r [[pid.]tty[.host]]screen -r sessionowner/[[pid.]tty[.host]]DESCRIPTIONScreen 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 (ECMA48, ANSI X3.64) and ISO 2022 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.
主要用于原有命令的补救措施,通过作业调度实现,是个较强大的命令。
disown -h jobspec 使某个作业忽略HUP信号。disown -ah 使所有的作业都忽略HUP信号。disown -rh 使正在运行的作业忽略HUP信号。
针对已有运行命令的实现策略有两种:
- [command] &将命令放到后台,再调用disown -h
- CTRL-Z挂起进程后,将作业放入后台继续运行,再调用disown -h
CTRL-Z的用途就是将当前进程挂起,然后我们就可以用jobs命令来查询它的作业号,再用bg jobspec来将它放入后台并继续运行。需要注意的是,如果挂起会影响当前进程的运行结果,请慎用此方法。
# 查看任务,返回任务编号n和进程号jobs -l# 挂起当前任务ctrl+z# 将编号为n的任务转后台运行bg %n# 将编号为n的任务转前台运行fg %n# 结束当前任务ctrl+c / ctrl+\# 设置程序父进程为1,不中断setsid ./test.sh &# 查看指定任务详细ps -ef | grep test# 显示当窗口父进程IDecho $$
#让进程在后台运行command&#查看后台运行的进程jobs#让后台运行的进程n到前台来fg %n#让进程n到后台去bg %n
#列出系统中正在运行的进程ps#发送信号给一个或多个进程(经常用来杀死一个进程)kill/killall/pkill#显示进程树状态pstree#显示进程top#查询匹配egrep#改变优先权renice#跟踪系统进程调用strace#跟踪进程调用库函数ltrace