(1):bash son.sh
cat /root/son.sh
#!/bin/bash
echo 1
[root@boy ~]# bash son.sh
1
`夯住`
# 夯住时
├─sshd(1076)───sshd(12592)─┬─bash(12596)───bash(12827)───sleep(12828)
└─bash(12673)───pstree(12829)
# 当执行完成后,子shell会回到父shell中
├─sshd(1076)───sshd(12592)─┬─bash(12596)
└─bash(12673)───pstree(12831)
(2):bash son.sh(夯住)
cat /root/son.sh
#!/bin/bash
while :
do
echo 1 >>/root/son.log
sleep 10
done
[root@boy ~]# bash son.sh
`卡住`
├─sshd(1076)───sshd(12592)─┬─bash(12596)───bash(12876)───sleep(12877)
└─bash(12673)───pstree(12879)
#分析:
12596为登录时生成的那个bash,在我执行bash son.sh后,生成了一个子bash(12876),且在执行son.sh时12596会夯住(阻塞在那了,等待子bash执行完成,但是我son.sh会无限循环的,意味着子bash永远不会返回,也就是用户在12596那个shell上无法操作)
(3):bash son.sh &
cat /root/son.sh
#!/bin/bash
while :
do
echo 1 >>/root/son.log
sleep 10
done
[root@boy ~]# bash son.sh &
[1] 13089
[root@boy ~]# jobs
[1]+ Running bash son.sh &
[root@boy ~]# echo $BASHPID
12596
├─sshd(1076)───sshd(12592)─┬─bash(12596)───bash(13089)───sleep(13099)
└─bash(12673)───pstree(13100)
# 分析:
生成子bash方式与(2)没有多大区别,唯一的区别就是加了&后,13089放在后台去执行了,12596还可以进行其他操作
(4):source son.sh
cat /root/son.sh
#!/bin/bash
while :
do
echo 1 >>/root/son.log
sleep 10
done
[root@boy ~]# source son.sh
`卡住`
├─sshd(1076)───sshd(12592)─┬─bash(12596)───sleep(13133)
└─bash(12673)───pstree(13134)
# 分析
使用source后,父bash不会生成子bash,但是存在12596这个bash夯在前台了
(5):source son.sh &
cat /root/son.sh
#!/bin/bash
while :
do
echo 1 >>/root/son.log
sleep 10
done
[root@boy ~]# source son.sh &
[1] 13151
[root@boy ~]# echo $BASHPID
12596
├─sshd(1076)───sshd(12592)─┬─bash(12596)───bash(13151)───sleep(13152)
└─bash(12673)───pstree(13153)
# 分析:
通过观察可以发现,不管是使用bash、source执行脚本,只要后面加了&放后台执行,都会生成子shell,12596此时能接受用户输入
(6):nohub bash son.sh &
cat /root/son.sh
#!/bin/bash
while :
do
echo 1 >>/root/son.log
sleep 10
done
[root@boy ~]# nohup bash son.sh &
[1] 13284
[root@boy ~]# nohup: ignoring input and appending output to ‘nohup.out’
[root@boy ~]# echo $BASHPID
13248
├─sshd(1076)───sshd(12592)─┬─bash(12673)───pstree(13287)
└─bash(13248)───bash(13284)───sleep(13286)
# 13248 执行exit后
├─bash(13284)───sleep(13298)
├─sshd(1076)───sshd(12592)───bash(12673)───pstree(13299)
# 分析
可以发现13284在用户退出登陆后,任然在后台执行
(7):nohub source son.sh &
cat /root/son.sh
#!/bin/bash
while :
do
echo 1 >>/root/son.log
sleep 10
done
[root@boy ~]# nohup source son.sh &
[1] 13440
[root@boy ~]# nohup: ignoring input and appending output to ‘nohup.out’
nohup: failed to run command ‘source’: No such file or directory
# 如果用nohub 执行java等相关命令也显示没有时,脚本开头加上
source /etc/profile 等,引入变量
结论:
- 平常在rc.local或者cron中运行其他脚本的时候需要根据调用的脚本是否会夯住,灵活使用nohub和&,解决rc.local,cron中其他内容没有执行