linuxnor命令 linux命令nice( 二 )


回页首
disown
场景:
我们已经知道,如果事先在命令前加上 nohup 或者 setsid 就可以避免 HUP 信号的影响 。但是如果我们未加任何处理就已经提交了命令,该如何补救才能让它避免 HUP 信号的影响呢?
解决方法:
这时想加 nohup 或者 setsid 已经为时已晚,只能通过作业调度和 disown 来解决这个问题了 。让我们来看一下 disown 的帮助信息:
disown [-ar] [-h] [jobspec ...]
Without options, each jobspec isremovedfromthetableof
activejobs.Ifthe -h option is given, each jobspec is not
removed from the table, but is marked sothatSIGHUPisnot
sentto the job if the shell receives a SIGHUP.If no jobspec
is present, and neither the -a nor the -r optionissupplied,
thecurrentjobisused.If no jobspec is supplied, the -a
option means to remove or mark all jobs; the -r optionwithout
ajobspecargumentrestricts operation to running jobs.The
return value is 0 unless a jobspec doesnotspecifyavalid
job.
可以看出 , 我们可以用如下方式来达成我们的目的 。
灵活运用 CTRL-z

我们的日常工作中 , 我们可以用 CTRL-z 来将当前进程挂起到后台暂停运行,执行一些别的操作 , 然后再用 fg 来将挂起的进程重新放回前台(也可用
bg
来将挂起的进程放在后台)继续运行 。这样我们就可以在一个终端内灵活切换运行多个任务,这一点在调试代码时尤为有用 。因为将代码编辑器挂起到后台再重新放
回时,光标定位仍然停留在上次挂起时的位置,避免了重新定位的麻烦 。
用disown -h jobspec来使某个作业忽略HUP信号 。
用disown -ah 来使所有的作业都忽略HUP信号 。
用disown -rh 来使正在运行的作业忽略HUP信号 。
需要注意的是,当使用过 disown 之后,会将把目标作业从作业列表中移除,我们将不能再使用jobs来查看它,但是依然能够用ps -ef查找到它 。
但是还有一个问题,这种方法的操作对象是作业,如果我们在运行命令时在结尾加了""来使它成为一个作业并在后台运行,那么就万事大吉了,我们可以通过jobs命令来得到所有作业的列表 。但是如果并没有把当前命令作为作业来运行,如何才能得到它的作业号呢?答案就是用 CTRL-z(按住Ctrl键的同时按住z键)了!
CTRL-z 的用途就是将当前进程挂起(Suspend),然后我们就可以用jobs命令来查询它的作业号,再用bg jobspec来将它放入后台并继续运行 。需要注意的是,如果挂起会影响当前进程的运行结果,请慎用此方法 。
disown 示例1(如果提交命令时已经用“”将命令放入后台运行,则可以直接使用“disown”)
[root@pvcent107 build]# cp -r testLargeFile largeFile
[1] 4825
[root@pvcent107 build]# jobs
[1]+Runningcp -i -r testLargeFile largeFile
[root@pvcent107 build]# disown -h %1
[root@pvcent107 build]# ps -ef |grep largeFile
root48259681 09:46 pts/400:00:00 cp -i -r testLargeFile largeFile
root48539680 09:46 pts/400:00:00 grep largeFile
[root@pvcent107 build]# logout
disown 示例2(如果提交命令时未使用“”将命令放入后台运行,可使用 CTRL-z 和“bg”将其放入后台 , 再使用“disown”)
[root@pvcent107 build]# cp -r testLargeFile largeFile2
[1]+Stoppedcp -i -r testLargeFile largeFile2
[root@pvcent107 build]# bg %1
[1]+ cp -i -r testLargeFile largeFile2
[root@pvcent107 build]# jobs
[1]+Runningcp -i -r testLargeFile largeFile2
[root@pvcent107 build]# disown -h %1
[root@pvcent107 build]# ps -ef |grep largeFile2
root579055771 10:04 pts/300:00:00 cp -i -r testLargeFile largeFile2
root582455770 10:05 pts/300:00:00 grep largeFile2

推荐阅读