1. 准备一个测试脚本service.sh, 用于模拟一个服务程序。真实情况下可以是任意可执行程序或脚本
cd /
[root@localhost /]# vim service.sh
#!/bin/bash
while [ 1 ]
do
echo `date` >> /tmp/d.log
sleep 1
done
2. 创建chkconfig服务脚本(CentOS7是用systemd管理服务,但是兼容chkconfig。相对而言chkconfig更加简单)
[root@localhost init.d]# cd /etc/init.d/
[root@localhost init.d]# cp network myservice
[root@localhost init.d]# vim myservice
直接拷贝network(用作参考!),然后编辑myservice内容如下
#! /bin/bash
#
# myservice myservice
#
# chkconfig: 2345 10 90
# description: myservice description...
#
# See how we were called.
case "$1" in
start)
sh /service.sh
;;
stop)
pid=`ps aux | grep "/service.sh" | grep -v grep | awk '{print $2}'`
kill $pid
;;
status)
ps aux | grep "/service.sh"
;;
restart|reload|force-reload)
cd "$CWD"
$0 stop
$0 start
rc=$?
;;
*)
echo $"Usage: $0 {start|stop|status|restart|reload|force-reload}"
exit 2
esac
exit 0
3. 添加到chkconfig服务列表,开机启动
[root@localhost init.d]# chkconfig --add myservice
[root@localhost init.d]# chkconfig myservice on
[root@localhost init.d]# chkconfig | grep myservice
Note: This output shows SysV services only and does not include native
systemd services. SysV configuration data might be overridden by native
systemd configuration.
If you want to list systemd services use 'systemctl list-unit-files'.
To see services enabled on particular target use
'systemctl list-dependencies [target]'.
myservice 0:off 1:off 2:on 3:on 4:on 5:on 6:off
可以看到,已经添加到启动列表。由于没有使用systemd,打印了提示信息,做一个简单的服务无需理会。
4. 重启系统,检查服务是否正常启动(线上系统不要随意重启!!!,此处仅仅为了验证开机能否自启动)
[root@localhost init.d]# reboot
。
。
[root@localhost ~]# ps aux | grep /service
root 674 0.0 0.1 115256 1540 ? S 10:52 0:00 sh /service.sh
root 1325 0.0 0.0 112656 968 pts/0 S+ 10:54 0:00 grep --color=auto /service
[root@localhost ~]# tail -f /tmp/d.log
2017年 12月 28日 星期四 10:54:20 CST
2017年 12月 28日 星期四 10:54:21 CST
2017年 12月 28日 星期四 10:54:22 CST
2017年 12月 28日 星期四 10:54:23 CST
2017年 12月 28日 星期四 10:54:24 CST
2017年 12月 28日 星期四 10:54:25 CST
2017年 12月 28日 星期四 10:54:26 CST
2017年 12月 28日 星期四 10:54:27 CST
2017年 12月 28日 星期四 10:54:28 CST
2017年 12月 28日 星期四 10:54:29 CST
2017年 12月 28日 星期四 10:54:30 CST
2017年 12月 28日 星期四 10:54:31 CST
2017年 12月 28日 星期四 10:54:32 CST
^C
可以看到程序成功启动并且正常执行