2020年4月25日更新:

  • screen中若中文乱码,可以添加-U参数指定UTF-8编码。
  • CTRL-a d的实际操作方法为按住CTRL后再依次按下a与d。

概览

进几日在运行zmap扫描的时候,zmap进程总会随着终端的退出而停止。究其原因,即是终端关闭时候的HUP(hangup)信号影响了该终端所在的会话下的全部进程,也就是说,bash等进程会被清除。

解决办法既有两个:

·忽略系统发出的HUP信号。

·使进程成为其它会话下的子进程并不再接收当前会话的HUP信号。

忽略HUP信号

nohup

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 root@raincorn:~# nohup --help
Usage: nohup COMMAND [ARG]...
or: nohup OPTION
Run COMMAND, ignoring hangup signals.

--help display this help and exit
--version output version information and exit

If standard input is a terminal, redirect it from an unreadable file.
If standard output is a terminal, append output to 'nohup.out' if possible,
'$HOME/nohup.out' otherwise.
If standard error is a terminal, redirect it to standard output.
To save output to FILE, use 'nohup COMMAND > FILE'.

NOTE: your shell may have its own version of nohup, which usually supersedes
the version described here. Please refer to your shell's documentation
for details about the options it supports.

GNU coreutils online help: <http://www.gnu.org/software/coreutils/>
Full documentation at: <http://www.gnu.org/software/coreutils/nohup>
or available locally via: info '(coreutils) nohup invocation'

(以上为nohup的帮助页面)
例:

1
nohup ping g.cn &

此处的&代表将命令在后台运行,若要结束进程,可以使用ps -ef |grep ping来查找执行ping的进程,再使用kill pid来结束进程。

disown


disown -h %1

用disown -h jobspec来使某个进程忽略HUP信号。

用disown -ah 来使所有的进程都忽略HUP信号。

用disown -rh 来使正在运行的进程忽略HUP信号。

在前台执行命令后,可以考虑将其放到后台并挂起,待查阅到相应的进程信息后再恢复并作处理。

其中:

jobs—查看后台进程

ctrl+z —将当前进程挂起到后台

ctrl+c—取消前台进程

bg %n—继续执行后台进程(其中n为进程编号,通过jobs获取)

fg %n—将后台进程移至前台。

kill %n—结束进程编号为n的进程

转移进程会话

setsid


setsid ping raincorn.top

运行之后发现进程的PPID变为init,也就是说,此时的进程在终端会话的父进程之外,此时的HUP信号自然不会影响我们所需要的进程。

&


(ping raincorn.top &)

此时的现象与执行setsid类似,处理后的进程被置于终端子进程之外。

screen

screen可以提供一个伪全屏终端,可以在screen提供的终端下进行操作,此时的进程便被置于screen的子目录下,不受终端HUP信号影响,由于软件的管理特性,因此适于大批量处理命令。

用screen -dmS session name来建立一个处于断开模式下的会话(并指定其会话名)。

用screen -list 来列出所有会话。

用screen -r session name来重新连接指定会话。

用快捷键CTRL-a d 来暂时断开当前会话。

总结

·nohup,setside,&的使用适用于小批量并在命令执行的时候使用。

·当执行对应命令之后则需使用disown进行补救。

·对于大批量的命令要求,则可以使用screen,在不同子会话下创建不同进程并可以来回切换。