Ubuntu添加开机启动脚本

新建一个shell脚本,内容如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/bin/bash

### BEGIN INIT INFO
# Provides: protected_shell
# Required-Start: $local_fs $remote_fs $network $syslog $named
# Required-Stop: $local_fs $remote_fs $network $syslog $named
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: protect the gdwy_device_server
### END INIT INFO

# chkconfig: - 60 50
# description: service demo script
# processname: service_demo

# Source function library.
#./etc/init.d/functions

# Source networking configuration.
#./etc/sysconfig/network

# Check that networking is up.
#[ ${NETWORKING}="no" ] && exit 0

#进程名字可修改
PRO_NAME=/home/liurui/test1/build-test1-64bit-Debug/test1
CMD="$PRO_NAME "
#exec permission
[ -x $PRO_NAME ] || exit 0


while true ; do
#用ps获取$PRO_NAME进程数量
NUM=`ps aux | grep -w ${PRO_NAME} | grep -v grep |wc -l`
echo $NUM
#少于1,重启进程
if [ "${NUM}" -lt "1" ];then
echo "${PRO_NAME} was killed"
$CMD
#大于1,杀掉所有进程,重启
elif [ "${NUM}" -gt "1" ];then
echo "more than 1 ${PRO_NAME},killall ${PRO_NAME}"
killall -9 $PRO_NAME
$CMD
fi
#kill僵尸进程
NUM_STAT=`ps aux | grep -w ${PRO_NAME} | grep T | grep -v grep | wc -l`
if [ "${NUM_STAT}" -gt "0" ];then
killall -9 ${PRO_NAME}
echo "zombie was killed"
$CMD
fi
sleep 5s
done
echo "shell was killed"
exit 0

如果不添加前面的启动信息(BEGIN INIT INFO)会报错,如下:

1
2
3
4
5
6
7
8
9
10
11
12
insserv: warning: script 'protected_shell' missing LSB tags and overrides

insserv: There is a loop between service watchdog and protected_shell if stopped

insserv: loop involving service protected_shell at depth 2
insserv: loop involving service watchdog at depth 1

insserv: Stopping protected_shell depends on watchdog and therefore on system facility `$all' which can not be true!

insserv: exiting now without changing boot order!

update-rc.d: error: insserv rejected the script header

主要是因为脚本的启动顺序和其它服务冲突导致,同时没有配置脚本启动的级别
赋予执行权限

1
2
3
chmod +x test.sh

sudo mv test.sh /etc/init.d/

添加开机启动

1
sudo update-rc.d test.sh defaults

取消开机启动

1
sudo update-rc.d -f test.sh remove

Ubuntu添加开机启动脚本
http://yoursite.com/2019/01/31/Ubuntu添加开机启动脚本/
作者
还在输入
发布于
2019年1月31日
许可协议