linux注册服务启动项,如何创建一个最简单的Linux自启动服务?

最鸡蛋的方法是把命令写到/etc/rc.d/rc.local或者/etc/rc.local里,这样虽然能够实现随机运行,但是并不够灵活。不能像mysql,apache等服务一样能够使用service命令或者调用init.d下的脚本启动、关闭或者重启进程。

$ service mysql restart

$ service apache2 stop

因为不同的Linux发行版本,对后台服务的处理方式不大一样,所以下面以Ubuntu系统为例,看看如何写一个简单的随机自启动服务。

准备好一个需要随机启动的程序,比如:/root/auto.py,设置可执行属性,确保可以通过输入绝对路径直接执行。

$ chmod +x auto.py

$ /root/auto.py

It's work.

编写一个启动控制脚本,以auto为例,建立/etc/init.d/auto文本文件,输入下面的内容:

#!/bin/sh

case "$1" in

start)

start-stop-daemon --start --background --exec /root/auto.py

;;

stop)

start-stop-daemon --stop --name auto.py

esac

这是一个简单的shell脚本,case .. in是用来根据调用参数进行不同的操作,start-stop-daemon是一个可以管理daemon进程的程序,要查看它的详细说明,可以运行man start-stop-daemon查看。start的时候使用--exec指定要执行的文件,stop的时候,使用--name根据进程名字来使用killall结束匹配的进程。

接着,设置脚本文件属性,设置可执行标记。

$ chmod 755 /etc/init.d/auto

这样子,就可以使用service命令来启动和关闭进程了。

启动进程:

$ service proxy start

$ ps aux|grep proxy

root 353 1.4 1.9 8644 5212 ? S 09:50 0:00 /usr/bin/python /root/auto.py

root 355 0.0 0.2 1900 596 pts/0 S+ 09:50 0:00 grep --color=auto auto

关闭进程:

$ service auto stop

$ ps aux |grep auto

root 365 0.0 0.2 1900 592 pts/0 S+ 09:51 0:00 grep --color=auto auto

到这里,一个Linux服务的进程控制脚本已经写好了,但是要实现随机启动,还需要一个步骤。

Linux开机的时候,不是直接运行/etc/init.d下的所有脚本的,而是根据不同的runlevel来执行/etc/rc$runlevel.d下的脚本。这里的runlevel是用以区别系统的运行方式(例如单用户的runlevel,多媒体桌面的runlevel,服务器的runlevel都不同)。

在Ubuntu里,可以使用update-rc.d来把/etc/init.d/auto安装到各个runlevel中。更多关于update-rc.d的说明,请参见man update-rc.d。

$ update-rc.d auto defaults 99

update-rc.d: warning: /etc/init.d/auto missing LSB information

update-rc.d: see

Adding system startup for /etc/init.d/auto ...

/etc/rc0.d/K99auto -> ../init.d/auto

/etc/rc1.d/K99auto -> ../init.d/auto

...

update-rc.d后面有三个参数,分别是/etc/init.d下的脚本名字,默认安装方式,运行的优先级。优先级的数字越大,表示越迟运行,这里我们把自己写的服务放在最后运行。

如果要卸载随机启动的服务,执行

$ update-rc.d -f auto remove

在update-rc.d安装的时候提示了警告信息,是因为我们写的/etc/init.d/auto太简陋了,连LSB的信息也没有提供。

update-rc.d: warning: /etc/init.d/auto missing LSB information

update-rc.d: see

只需要做一些小改动,就可以避免那个警告了。如下:

#!/bin/sh

### BEGIN INIT INFO

# Provides: auto

# Default-Start: 2 3 4 5

# Default-Stop: 0 1 6

# Short-Description: Start or stop a program.

### END INIT INFO

case "$1" in

start)

start-stop-daemon --start --background --exec /root/auto.py

;;

stop)

start-stop-daemon --stop --name auto.py

esac

到此,一个最简单的随机启动服务写好了,看起来文章挺长的,但其实也就几个命令而已。

在下次开机启动的时候,auto.py就会以root用户身份被自动运行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值