最近着手导师分配的项目任务,对Linux有了一定基础的了解,项目其中有要求在Linux部署一个开机自启动服务。本文将以此为目的来探索如何实现开机自启动服务。
GNU/Linux实现开机自启动服务有两种方式:
SysVinit
systemd
SysVinit
SysVinit作为init进程执行/etc/init.d/中的脚本,这些脚本称为“服务”,每个run level所对应的目录/etc/rcX.d/都存放这指向/etc/init.d/的链接,其中X=0, 1, 2, 3, 4, 5, 6对应不同的运行级别,S比较特殊,init进程作为1号进程启动后,会在开始对应运行级别的服务之前开始/etc/rcS.d中的服务。
运行级别
关机
单用户模式
多用户模式(没有NFS)
多用户模式
保留
x window模式(图形界面)
重启
/etc/init.d中的服务样式如下:
#!/bin/bash
start() {
# 你要执行的程序或脚本
}
stop() {
...
}
# shell脚本中,$0表示自身shell脚本对于当前执行路径的相对名称
# 从$1开始表示接收的参数
# example:
# cd ~
# sh start.sh hello
# $0: start.sh
# $1: hello
switch $1 in
case
start)
start
;;
stop)
stop
;;
*)
...
esac
exit 0
这样的脚本,我们称之为服务(service)
基于SysVinit编写自启动流程
具体流程如下:
在/etc/init.d中创建服务脚本hello
#!/bin/bash
# service hello
start() {
echo 'start hello service...'
/bin/BootLoader
echo 'start hello service over'
}
stop() {
echo 'stop hello service...'
killall BootLoader
echo 'stop hello service over'
}
switch $1 in
case
start)
start
;;
stop)
stop
;;
restart)
stop
start
*)
echo "valid arg:[start|status|stop|restart]"
esac
exit 0
status 是自带的参数,用于查看服务状态
保存脚本后,通过sysv-rc-conf或chkconfig(Red Hat Linux)命令设置服务在什么运行等级开机启动
apt install定位不到sysv-rc-conf包解决方案:https://www.cnblogs.com/hester/p/12254562.html
通过service命令可以管理所写的服务:
service hello start // 启动nginx服务
service hello status // 查看服务运行状态
service hello stop // 关闭nginx服务
systemd
SysVinit 运行非常良好,概念简单清晰。它主要依赖于 Shell 脚本,这就决定了它的最大弱点:启动太慢。在很少重新启动的Server 上,这个缺点并不重要。而当 Linux 被应用到移动终端设备的时候,启动慢就成了一个大问题。
随着Linux的更新,sysvinit程序被systemd取代。
systemd的特点是可以让服务之间并行启动,加快Linux启动速度。(systemd不仅仅是管理开机,作为一号进程,它几乎什么都管)
systemd中的systemctl命令可以对服务进行管理。
systemd的服务保存于/etc/systemd/system中, 服务样式如下:
[Unit]
Description=This is a simple service
# 表示本服务在network.target启动后启动(如果networdk.target启动的话)
After=network.target
# 若依赖
Wants=sshd-keygen
# 强依赖
Requires=
[Service]
# simple指ExecStart启动的进程为主进程
Type=simple
ExecStart=...your program address
# 定义如何安装这个配置文件
[Install]
#
WantedBy=multi-user.target
[Unit]
[Unit] 用于描述服务以及指定该服务与其他服务启动的优先次序
[Service]
[Service]用于描述如何启动当前服务。
[Install]
[Install]定义如何安装这个配置文件,即怎样做到开机启动。
WantedBy字段:表示该服务所在的Target。
Target的含义是服务组,表示一组服务。WantedBy=multi-user.target指的是,该服务所在的Target是multi-user.target。
这个设置非常重要,因为执行systemctl enable hello.service命令时,hello.service的一个符号链接,就会放在/etc/systemd/system目录下面的multi-user.target.wants子目录之中。
Systemd 有默认的启动 Target,通过如下命令获得:
$ systemctl get-default
修改配置文件以后,需要重新加载配置文件,然后重新启动相关服务。
重新加载配置文件
修改了配置文件需要重新加载一下配置文件:
sudo systemctl daemon-reload
重启相关服务
sudo systemctl restart foobar
来源:oschina
链接:https://my.oschina.net/StupidZhe/blog/4411429