网上有不少关于如何让Linux自动运行自己编写的脚本或者程序的方法,但是大多数都是把命令写到/etc/rc.d/rc.local或者/etc/rc.local里,这样虽然能够实现随机运行,但是并不够灵活。不能像mysql,apache等服务一样能够使用service命令或者调用init.d下的脚本启动、关闭或者重启进程。例如,
service mysql restart
service apache2 stop
或者
/etc/init.d/mysql restart
/etc/init.d/apache2 stop
因为不同的Linux发行版本,对后台服务的处理方式不大一样,所以下面以centos系统为例,看看如何写一个简单的随机启动服务。
在/etc/init.d下面编写一个测试脚本
- [root@hostnfsd :/etc/init.d]$ more mysql-proxy
- #!/bin/sh
-
- case "$1" in
- start)
- echo "you start success"
- ;;
- stop)
- echo "you stop success"
- esac
[root@hostnfsd :/etc/init.d]$ chmod 755 mysql-proxy
这样就可以使用service 来控制了
[root@hostnfsd :/etc/init.d]$ /etc/init.d/mysql-proxy start
you start success
[root@hostnfsd :/etc/init.d]$ /etc/init.d/mysql-proxy stop
you stop success
到这里,一个Linux服务的进程控制脚本已经写好了,但是要实现随机启动,还需要一个步骤。 Linux开机的时候,不是直接运行/etc/init.d下的所有脚本的,而是根据不同的runlevel来执行/etc/rc$runlevel.d下的脚本。这里的runlevel是用以区别系统的运行方式(例如单用户的runlevel,多媒体桌面的runlevel,服务器的runlevel都不同)。
- 小小的修改一下就行了
- #!/bin/sh
- # chkconfig: 2345 20 81 --加上运行级别以
- #description: bymyself --加上描述
-
- case "$1" in
- start)
- echo "you start success"
- ;;
- stop)
- echo "you stop success"
- esac
- case "$1" in
[root@hostnfsd :/etc/init.d]$ chkconfig --add mysql-proxy
[root@hostnfsd :/etc/init.d]$ chkconfig --list | grep -i mysql
mysql-proxy 0:off 1:off 2:on 3:on 4:on 5:on 6:off
接下来开机就可以自启动这个脚本了
[root@hostnfsd :/etc/init.d]$ chkconfig --list | grep -i mysql
mysql-proxy 0:off 1:off 2:on 3:on 4:on 5:on 6:off
接下来开机就可以自启动这个脚本了
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/29096438/viewspace-2059578/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/29096438/viewspace-2059578/