【shell】linux在在脚本后台运行程序和直接在终端后台启的不同

【shell】linux在在脚本后台运行程序和直接在终端后台启的不同

时间:2013-08-09 10:08:23      作者:beebol      标签: init Linux shell      分类: Linux Shell

今天突然接到一个电话,需要确定一下某程序是否已经启服。登录服务器查看时,果然不在了。后来问了一下操作的同学(实习生),结果是直接在终端启的程序,因为终端的seession是有时间限制的,在一定的时间内没有使用就会断开。终端一断,那么程序也就掉了。这最主要的原因是在我,没有让他记住启程序的脚本在哪里?

我解释了具体的原因,不知道明白了没?在这里我详细地说明一下,并做下具体的例子:

1、先写一个简单的脚本:while.sh

!/bin/bash

for i in seq 100 do echo $i sleep 3 done exit 0

2、然后通过sh while.sh  &这种方式来启动

[root@localhost Desktop]# sh while.sh & [1] 24945

3、查看是存在的

[root@localhost ~]# ps -eo pid,ppid,cmd | grep while.sh 24945 23533 sh while.sh 24970 24113 grep while.sh

4、然后我将终端断开,发现已经没有再运行了

[root@localhost ~]# ps -eo pid,ppid,cmd | grep while.sh 24998 24113 grep while.sh

这说明:直接以command  & 这种方式启,终端断开后,程序退出。

如果我们在脚本里启动呢?先写一个a.sh脚本来启动while.sh脚本。

[root@localhost Desktop]# cat a.sh sh while.sh >/dev/null & sleep 20         #这里的等待20秒是为了父shell慢点退出

1、启动a.sh 

[root@localhost Desktop]# sh a.sh

 2、查看,while.sh还在25191进程下面运行

[root@localhost ~]# ps -eo pid,ppid,cmd | grep while.sh 25192 25191 sh while.sh 25197 24113 grep while.sh

3、当这个脚本执行完毕后,或主动断开,再看

[root@localhost Desktop]# sh a.sh [root@localhost Desktop]#

4、它已经运行到init进程下了,就算整个终端断开也不会退出

[root@localhost ~]# ps -eo pid,ppid,cmd | grep while.sh 25192 1 sh while.sh 25273 24113 grep while.sh

为什么会这样呢?具体原因是while.sh是在subshell中启动的,当父shell结束或终止后。子进程就成了孤儿进程,它会自动转到init下运行。

当然linux下后台启动的方法还有好多,如:

nohup   command  &

setsid    command   &

(command  &)

screen  -dmS    name

screen -r  name

 

 

时间:2013-08-09 10:08:23      作者:beebol      标签: init Linux shell      分类: Linux Shell
  • 分享到:
  • 微博
  • QQ空间
  • 腾讯微博
  • 微信

Copyright © 2015 Gitblog | Proudly powered by Gitblog.