service
service格式
[Unit]
Description=服务描述
After=服务依赖(再这些服务后启动本服务)
[Service]
Type=服务类型
ExecStart=启动命令
ExecStop=终止命令
ExecReload=重启命令
[Install]
WantedBy=服务安装设置
这些文件位于/usr/lib/systemd/system目录下
[Unit]中After的值一般是:network.target remote-fs.target nss-lookup.target。
[Install]的WantedBy一般是multi-user.target。
service的类型
Type=oneshot
这一选项适用于只执行一项任务、随后立即退出的服务。可能需要同时设置 RemainAfterExit=yes 使得 systemd 在服务进程退出之后仍然认为服务处于激活状态。
Type=notify
与 Type=simple 相同,但约定服务会在就绪后向 systemd 发送一个信号。这一通知的实现由 libsystemd-daemon.so 提供。
Type=dbus
若以此方式启动,当指定的 BusName 出现在DBus系统总线上时,systemd认为服务就绪。
Type=idle systemd
会等待所有任务处理完成后,才开始执行 idle 类型的单元。其他行为与 Type=simple 类似。
Type=forking systemd
认为当该服务进程fork,且父进程退出后服务启动成功。对于常规的守护进程(daemon),除非你确定此启动方式无法满足需求,使用此类型启动即可。使用此启动类型应同时指定 PIDFile=,以便 systemd 能够跟踪服务的主进程
Type=simple
(默认值) systemd认为该服务将立即启动。服务进程不会 fork 。如果该服务要启动其他服务,不要使用此类型启动,除非该服务是socket 激活型。
** 一般来说我们的程序是应用程序前台使用就用simple,后台/守护进程一般是forking**
出现的问题
shelltest1.service: Failed to execute command: Permission denied;
加权限,写chmod 777 test1.sh
shelltest1.service: Failed at step EXEC spawning /home/sen/shelltest/test1.sh: Permission denied shelltest1.service: Service has more than o
加权限
ExecStart= setting, which is only allowed for Type=oneshot services. Refusing.
一个service中只能写一个exestart,如要两个可以写两个service
操作命令
# 开启服务,绝对地址
systemctl enable /home/sen/shelltest/shelltest1.service
# 修改service后重启服务
systemctl daemon-reload
# 现在运行程序
systemctl start shelltest1.service
# 查看程序状态
systemctl status shelltest1.service
案例
shelltest1.service
[Unit]
Description=servicetest1
After = syslog.target
[Service]
Type = simple
ExecStart=/home/sen/shelltest/test1.sh
SuccessExitStatus = 255
# ExecStart=/home/sen/shelltest/test2.sh
# SuccessExitStatus = 254
[Install]
WantedBy=multi-user.target
test1.sh
#!/bin/bash
mkdir /home/sen/shelltest/testfile1
cd /home/sen/shelltest/testfile1
touch test.md
echo 'hello word' >>test.md
example
Why this PC does not have Chinese language?
In the /lib/systemd/system/rc.local.service
# SPDX-License-Identifier: LGPL-2.1+
#
# This file is part of systemd.
#
# systemd is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
# This unit gets pulled automatically into multi-user.target by
# systemd-rc-local-generator if /etc/rc.local is executable.
[Unit]
Description=/etc/rc.local Compatibility
Documentation=man:systemd-rc-local-generator(8)
ConditionFileIsExecutable=/etc/rc.local
After=network.target
[Service]
Type=forking
ExecStart=/etc/rc.local start
TimeoutSec=0
RemainAfterExit=yes
GuessMainPID=no
Then in the /etc/rc.local
#!/bin/sh -e
ip link set can0 type can bitrate 1000000
ip link set can0 up
cd /home/dino/WMJ_Hero/build
./watchdog
~
~