浅谈在Linux中如何将脚本做成系统服务开机自启动 存在一些情况,我们需要将某些脚本作为系统服务来运行。 比如:Tomcat、MongoDB等,如果每次手动cd指定目录下启动脚本。 一是比较麻烦,二是这些服务一般需要开机自启动。 这个时候将脚本写成服务就方便使用,可以直接service 服务名 start。 不需要手动敲出来复杂的文件路径。 提示: 以下操作设计到Linux的运行级别概念。 请参数--->浅谈Linux系统中的7种运行级别。 案例: 下面给出一个比较简单的案例 1、 #!/bin/bash #chkconfig:2345 66 77 #description:custom case '$1' in start) echo '启动$0服务!' ;; stop) echo '停止$0服务!' ;; restart|reload) $0 stop $0 start ;; *) echo '用法:$0 {start|stop|restart}' esac ~ 注意: #chkconfig 2345 66 77 #description:custom 这两行信息是固定的写法。 (1)、#chkconfig 2345 66 77: 2345 :表示的运行级别(即:/etc/rc.d/rc2.d~rc5.d) 66:S(start),优先级 77:K(kill),优先级 (2)、#description:此脚本的描述 2、 将脚本复制到/etc/init.d文件夹 原由: 执行完步骤3后会产生一系列的软连接文件 这些软连接文件实际指向/etc/init.d/下脚本文件 [root@kingdom shellFile]# cp custom.sh /etc/init.d/ [root@kingdom shellFile]# cd /etc/init.d/ [root@kingdom init.d]# ls 3、 将脚本添加到chkconfig [root@kingdom shellFile]# chkconfig --add custom.sh [root@kingdom shellFile]# chkconfig --list | grep custom.sh //这里的2 3 4 5跟我们脚本中定义的是一致的 custom.sh 0:off 1:off 2:on 3:on 4:on 5:on 6:off 此时在 2 3 4 5对应的/etc/rc.d/rc2.d~rc5.d目录中已经产生了相应的链接文件 这些链接文件实际是指向步骤2中的/etc/init.d/下脚本文件 以级别3为例 # ls /etc/rc.d/rc3.d/ ll S66custom.sh -> ../init.d/custom.sh 测试 [root@kingdom ~]# service custom.sh start 启动/etc/init.d/custom.sh服务! [root@kingdom ~]# service custom.sh stop 停止/etc/init.d/custom.sh服务! [root@kingdom ~]# service custom.sh restart 停止/etc/init.d/custom.sh服务! 启动/etc/init.d/custom.sh服务! 补充chkconfig的一些用法: //查看服务列表 chkconfig [--list] [--type type][name] //添加服务 chkconfig --add name //删除服务 chkconfig --del name //设置服务运行级别 chkconfig [--level levels] [--type type] name 欢迎大家给予宝贵的意见或者建议。 欢迎大家补充或者共享一些其他的方法。 感谢支持。 |
|