除了@ Michael Daffin的解决方案之外,您还可以使用守护程序工具来实现用法,forking
如以下示例所示。
给定一个我想守护并希望控制systemd的外壳程序脚本,我将其保存为/home/pi/testscript.sh
:
#!/bin/bash
while true;
do
sleep 1
echo -n "."
done
如果还没有,请安装守护进程,如下所示:
sudo apt install daemonize
现在创建文件服务定义文件:
sudo vi /etc/systemd/system/testomat.service
# It is not recommended to modify this file in-place, because it will
# be overwritten during package upgrades. If you want to add further
# options or overwrite existing ones then use
# $ systemctl edit testomat.service
# See "man systemd.service" for details.
# copied from https://github.com/bitcoin/bitcoin/blob/master/contrib/init/bitcoind.service and modified by Michael
[Unit]
Description=Test service
After=network.target
[Service]
ExecStart=daemonize -p /run/testomat/testomat.pid -o /home/pi/testscript.log /home/pi/testscript.sh
TimeoutSec=1200
# Make sure the config directory is readable by the service user
PermissionsStartOnly=true
# Process management
####################
Type=forking
PIDFile=/run/testomat/testomat.pid
Restart=on-failure
GuessMainPID = true
# Directory creation and permissions
####################################
# Run as pi:pi
User=pi
Group=pi
# /run/testomat
RuntimeDirectory=testomat
RuntimeDirectoryMode=0710
# /var/lib/testomat
StateDirectory=testomat
StateDirectoryMode=0710
# Hardening measures
####################
# Provide a private /tmp and /var/tmp.
PrivateTmp=true
# Mount /usr, /boot/ and /etc read-only for the process.
ProtectSystem=full
# Allow access to /home, /root and /run/user
# Chosing "false" is actually no hardening, this is just to demonstrate the usage of a service. Well, I could have omitted it. True. :)
ProtectHome=false
# Disallow the process and all of its children to gain
# new privileges through execve().
NoNewPrivileges=true
# Use a new /dev namespace only populated with API pseudo devices
# such as /dev/null, /dev/zero and /dev/random.
PrivateDevices=true
# Deny the creation of writable and executable memory mappings.
MemoryDenyWriteExecute=true
[Install]
WantedBy=multi-user.target
必须向systemd宣布新创建的服务:
systemctl daemon-reload
现在,您可以启动服务和脚本派生。如预期的那样,服务启动立即返回到外壳。结果很明显:
$ tail -f testscript.log
.....................
Type=forking
。而且,它不会execStart
作为shell扩展运行,因此&
最后永远不会被理解为背景标志。