linux 各种后台运行

来源:互联网 发布:ubuntu怎么安装apache 编辑:程序博客网 时间:2024/06/14 19:30

更加详细的解释说明:http://www.ibm.com/developerworks/cn/linux/l-cn-nohup/

我做了精简和简单的例子说明,也是为了自己写一遍加深一下印象

1. nohub sh run.sh &

nohup 无疑是我们首先想到的办法。顾名思义,nohup 的用途就是让提交的命令忽略 hangup 信号

使用:

[xluren@test ~]$ nohup ping baidu.com &[1] 31593[xluren@test ~]$ nohup: ignoring input and appending output to `nohup.out'[xluren@test ~]$ jobs[1]+  Running                 nohup ping baidu.com &[xluren@test ~]$ 

2.setsid同样能达到上面的功效

例子:

[xluren@test ~]$ setsid ping baidu.com >/dev/null [xluren@test ~]$ ps axf |grep baidu.com31813 pts/1    S+     0:00  |                       \_ grep baidu.com31811 ?        Ss     0:00 ping baidu.com[xluren@test ~]$ 

3.&和subshell

例子:

[xluren@test ~]$ (ping baidu.com  >/dev/null &)[xluren@test ~]$

4.disown

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 largeFileroot      4825   968  1 09:46 pts/4    00:00:00 cp -i -r testLargeFile largeFileroot      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 largeFile2root      5790  5577  1 10:04 pts/3    00:00:00 cp -i -r testLargeFile largeFile2root      5824  5577  0 10:05 pts/3    00:00:00 grep largeFile2[root@pvcent107 build]#

5.screen

用法:

执行完 screen ping baidu.com >/dev/null 后执行 ctrl+A+D 可以使任务后台运行 

[root@test ~]# screen ping baidu.com >/dev/null [detached][root@test ~]# screen -listThere is a screen on:31867.pts-1.test(Detached)1 Socket in /var/run/screen/S-root.[root@test ~]# 

 

现在几种方法已经介绍完毕,我们可以根据不同的场景来选择不同的方案。nohup/setsid 无疑是临时需要时最方便的方法,disown 能帮助我们来事后补救当前已经在运行了的作业,而 screen 则是在大批量操作时不二的选择了。



0 0