我有以下脚本:
whie true
do
#code
sleep 60
done
然后我想创建一个服务来启动机器并将这个脚本作为服务启动:在/etc/systemd/system/my.service 创建了 my.service
[Unit]
Description=my Script
[Service]
Type=forking
ExecStart=/bin/script.sh
[Install]
WantedBy=multi-user.target
当我 systemctl start my.service 出现问题它进入 while true 循环并卡在那里,我如何运行此服务并使其在后台运行?
最佳答案
根据 link 的 systemd 规范. Type=forking
在您的情况下不是完全正确的启动方式
If set to forking, it is expected that the process configured with ExecStart= will call fork() as part of its start-up. The parent process is expected to exit when start-up is complete and all communication channels are set up. The child continues to run as the main service process, and the service manager will consider the unit started when the parent process exits. This is the behavior of traditional UNIX services. If this setting is used, it is recommended to also use the PIDFile= option, so that systemd can reliably identify the main process of the service. systemd will proceed with starting follow-up units as soon as the parent process exits.
Type=simple
可以是正确的。你可以试试If set to simple (the default if ExecStart= is specified but neither Type= nor BusName= are), the service manager will consider the unit started immediately after the main service process has been forked off. It is expected that the process configured with ExecStart= is the main process of the service. In this mode, if the process offers functionality to other processes on the system, its communication channels should be installed before the service is started up (e.g. sockets set up by systemd, via socket activation), as the service manager will immediately proceed starting follow-up units, right after creating the main service process, and before executing the service's binary. Note that this means systemctl start command lines for simple services will report success even if the service's binary cannot be invoked successfully (for example because the selected User= doesn't exist, or the service binary is missing).
关于bash - Centos 7 创建服务以在无限循环上运行 shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68394018/