让进程在后台运行方法汇总
1. nohup
[root@pvcent107 ~]# nohup ping www.ibm.com &
nohup: appending output to `nohup.out'
[1] 3059
2.setsid
[root@pvcent107 ~]# setsid ping www.ibm.com
3.& in subshell
[root@pvcent107 ~]# (ping www.ibm.com &)
4.disown
如果我们未加任何处理就已经提交了命令,使用disown命令。
- 用
disown -h jobspec
来使某个作业忽略HUP信号。 - 用
disown -ah
来使所有的作业都忽略HUP信号。 - 用
disown -rh
来使正在运行的作业忽略HUP信号
jobs
来查看它,但是依然能够用ps -ef
查找到它。
这种方法的操作对象是作业,如果我们在运行命令时在结尾加了"&"来使它成为一个作业并在后台运行,那么就万事大吉了,我们可以通过jobs
命令来得到所有作业的列表。但是如果并没有把当前命令作为作业来运行,如何才能得到它的作业号呢?答案就是用 CTRL-z(按住Ctrl键的同时按住z键)了!
[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]#
5. screen
如果有大量这种命令需要在稳定的后台里运行,此时最方便的方法就是 screen 了。简单的说,screen 提供了 ANSI/VT100 的终端模拟器,使它能够在一个真实终端下运行多个全屏的伪终端。
使用 screen 很方便,有以下几个常用选项:
- 用
screen -dmS session name
来建立一个处于断开模式下的会话(并指定其会话名)。
- 用
screen -list
来列出所有会话。
- 用
screen -r session name
来重新连接指定会话。
- 用快捷键
CTRL-a d
来暂时断开当前会话。
[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