“nohup”

在用户ssh终端断开或者网络端口时,终端没有HUP信号则会关闭所有子进程。

nohup则会让进程忽略HUP信号,不受终端断开限制

一般在结尾加上“&”将命令同时放到中断后台运行

nohup标准输出和标准错误输出会被重定向到nohup.out文件中  

[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 ~]#


“&”

将一个或者多个命令包含在"()"中,就能让这些命令在子shell中运行

将"&"也放在"()"中,发现所提交的作业并不在作业列表中,也就是说,无法通过jobs来查看,从而躲过HUP信号的影响,不受中断断开的影响

[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信号影响。


“screen”

screen可以让大量命令能够在稳定的后台里运行

screen提供了ANSI/VT100的终端模拟器,能够在一个真实的终端下运行多个全屏的伪终端

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

在screen中执行命令时,不用担心HUP信号的影响,是因为:

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子进程,当sshd断开时,HUP信号自然会影响当前sshd下的所有子进程。

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/&无疑是临时需要时最方便的方法,screen则是在大批量且需要稳定环境的操作时的不二选择。