概要
利用 Linux 的 systemd,为 sh 脚本创建系统服务,实现开机自启。
步骤
脚本文件
1
2
|
#/bin/bash
echo "hello world"
|
服务配置
示例
系统服务目录(跟随系统启动):/usr/lib/systemd/system/
用户服务目录(用户登陆之后启动):/usr/lib/systemd/user/
文件名称:service-name.service
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
[UNIT]
# 服务描述
Description= some desctiption message...
# 指定在 systemd 在执行完哪些 target 之后再启动该服务
After=network.target
[Service]
# 服务类型,一般是 forking (后台运行)
Type=forking
#定义 systemctl start|stop|reload *.service 的执行方法(具体命令需要写绝对路径)
# 启动目标脚本前执行的命令
ExecStartPre=/usr/bin/test "x${NETWORKMANAGER}" = xyes
# 启动目标脚本的命令
ExecStart=/home/mobileoa/apps/shMediaManager.sh -start
# 重启服务
ExecReload=
# 停止服务
ExecStop=/home/mobileoa/apps/shMediaManager.sh -stop
#创建私有的内存临时空间
PrivateTmp=True
[Install]
#多用户
WantedBy=multi-user.target
|
说明
略。TODO
命令
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
# 设置 service-name 开机启动
systemctl enable service-name.service
# 重载系统服务
systemctl daemon-reload
# 启动服务
systemctl start service-name.service
# 停止服务
systemctl stop service-name.service
#重启服务
systemctl reload service-name.service
# 分析所有服务耗时
systemd-analyze critical-chain
# 列出所有开机自动启动的服务
systemctl list-unit-files --type=service | grep enabled
|
参考
【1】10分钟学会linux自定义服务(systemctl)_linux systemctl enable-CSDN博客
Preview: