通过如下命令
cat /etc/init.d/README
可以了解如果想让/etc/init.d目录下的脚本自启动需要在文件头写一个LSB格式的“头”,一些部分可以省去,具体说明可以查官网了解
### BEGIN INIT INFO
# Provides: skeleton
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Should-Start: $portmap
# Should-Stop: $portmap
# X-Start-Before: nis
# X-Stop-After: nis
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# X-Interactive: true
# Short-Description: Example initscript
# Description: This file should be used to construct scripts to be
# placed in /etc/init.d.
### END INIT INFO
我将我写好的protect_detect.sh脚本通过cp命令复制至/etc/init.d/目录下,这是一个进程守护脚本,具体内容如下
#!/bin/bash### BEGIN INIT INFO
# Provides: skeleton
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Should-Start: $portmap
# Should-Stop: $portmap
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Example initscript
### END INIT INFOPRO_NAME_2=/home/rock/Python_env/mp_env/code/DriveModuleDetect-main/main.pywhile true; doNUM_2=`ps aux | grep -w ${PRO_NAME_2} | grep -v grep | wc -l`if [ "${NUM_2}" -lt "1" ];thenecho "${PRO_NAME_2} was killed"bash /home/rock/Start_Shell/drive_detect.shfisleep 5s
doneexit 0
最后通过如下命令设置自启动,90代表优先级,数字越大越晚执行
sudo update-rc.d protect_detect.sh defaults 90
如果报错:
perl: warning: Setting locale failed.
perl: warning: Please check that your locale settings:
查看解决方法
不过这种方式设置后,我发现我仍需要切换至root用户才能成功设置,切换root用户命令:
sudo su
最后再使用如下命令即可成功设置
sudo update-rc.d protect_detect.sh defaults 90
最后reboot重启一下验证自己的脚本是否成功自启动
如果要移除自启动脚本,也是再root用户模式下,执行如下命令:
sudo update-rc.d protect_detect.sh remove
题外话:使用/etc/rc.local也可以实现自启动脚本,但是如果执行的脚本会发生循环阻塞,则无法执行其他的命令,因为我需要两个一直在后台循环执行的脚本,所以采用了/etc/init.d的方法,不过还是有些地方一知半解,欢迎一起交流。