$ ./test.sh &
[1] 17208
$ jobs -l
[1]+ 17208 Running ./test.sh &
对于已经在前台执行命令也可以重新放到后台执行首先按ctrl+z暂停已经运行进程然后使用bg命令将停止作业放到后台运行:
$ ./test.sh
[1]+ Stopped ./test.sh
$ bg %1
[1]+ ./test.sh &
$ jobs -l
[1]+ 22794 Running ./test.sh &
但是如上方到后台执行进程其父进程还是当前终端shell进程而旦父进程退出则会发送hangup信号给所有子进程子进程收到hangup以后也会退出如果我们要在退出shell时候继续运行进程则需要使用nohup忽略hangup信号或者sid将将父进程设为init进程(进程号为1)
$ echo $$
21734
$ nohup ./test.sh &
[1] 29016
$ ps -ef | grep test
515 29710 21734 0 11:47 pts/12 00:00:00 /bin/sh ./test.sh
515 29713 21734 0 11:47 pts/12 00:00:00 grep test
$ sid ./test.sh &
[1] 409
$ ps -ef | grep test
515 410 1 0 11:49 ? 00:00:00 /bin/sh ./test.sh
515 413 21734 0 11:49 pts/12 00:00:00 grep test
上面试验演示了使用nohup/sid加上&使进程在后台运行同时不受当前shell退出影响那么对于已经在后台运行进程该如何办呢?可以使用disown命令:
$ ./test.sh &
[1] 2539
$ jobs -l
[1]+ 2539 Running ./test.sh &
$ disown -h %1
$ ps -ef | grep test
515 410 1 0 11:49 ? 00:00:00 /bin/sh ./test.sh
515 2542 21734 0 11:52 pts/12 00:00:00 grep test
另外还有种思路方法即使将进程在个subshell中执行其实这和sid异曲同工思路方法很简单将命令用括号 括起来即可:
$ (./test.sh &)
$ ps -ef | grep test
515 410 1 0 11:49 ? 00:00:00 /bin/sh ./test.sh
515 12483 21734 0 11:59 pts/12 00:00:00 grep test
注:本文试验环境为Red Hat Enterprise Linux AS release 4 (Nahant Update 5),shell为/bin/bash区别OS和shell可能命令有些不样例如AIXksh没有disown但是可以使用nohup -p PID来获得disown同样效果
还有种更加强大方式是使用screen首先创建个断开模式虚拟终端然后用-r选项重新连接这个虚拟终端在其中执行任何命令都能达到nohup效果这在有多个命令需要在后台连续执行时候比较方便:
$ screen -dmS screen_test
$ screen -list
There is a screen _disibledevent=>http://www.ningoo.net/html/2008/how_to_run_processes_on_background_in_linux.html
最新评论