Systemd
是最初由Red Hat Linux团队开发的Linux系统工具。 它包括许多功能,包括用于启动和管理系统进程的引导系统。 当前,它是大多数Linux发行版中的默认初始化系统。 许多常用的软件工具(例如SSH和Apache)都附带有systemd服务,其成套封装使用起来相当方便,且并发启动大大增加了启动速度。
创建自定义systemd系统服务
1、新建example脚本helloworld.sh,输入以下内容:
DATE=`date '+%Y-%m-%d %H:%M:%S'`
echo "Example service started at ${DATE}"
echo "HelloWorld..."
2、脚本拷贝到/usr/bin路径,并赋予可执行权限:
sudo cp helloworld.sh /usr/bin/helloworld.sh
sudo chmod +x /usr/bin/helloworld.sh
3、在/lib/systemd/system/路径下新建文件(服务),文件名为helloworld.service:
[Unit]
Description=Example HelloWorld systemd service.
[Service]
Type=simple
ExecStart=/bin/bash /usr/bin/hellworld.sh
[Install]
WantedBy=multi-user.target
4、将 helloworld.service文件拷贝到/etc/systemd/system目录:
sudo cp /lib/systemd/system/helloworld.service /etc/systemd/system/helloworld.service
sudo chmod 644 /etc/systemd/system/helloworld.service
详细的systemd规则可以参考systemd documentation。
使能自定义systemd服务
1、一旦创建了service就可以用一下命令测试:
sudo systemctl start helloworld
2、 检查服务状态:
sudo systemctl status helloworld
输出结果如下:
● helloworld.service - Example HelloWorld systemd service.
Loaded: loaded (/etc/systemd/system/helloworld.service; disabled; vendor preset: enabled)
Active: inactive (dead)
5月 15 23:32:07 gohi-pc bash[3974]: HelloWorld...
5月 15 23:32:07 gohi-pc systemd[1]: helloworld.service: Succeeded.
5月 15 23:33:15 gohi-pc systemd[1]: Started Example HelloWorld systemd service..
5月 15 23:33:15 gohi-pc helloworld.sh[3997]: Example service started at 2020-05-15 23:33:15
5月 15 23:33:15 gohi-pc helloworld.sh[3997]: HelloWorld...
5月 15 23:33:15 gohi-pc systemd[1]: helloworld.service: Succeeded.
5月 15 23:37:14 gohi-pc systemd[1]: Started Example HelloWorld systemd service..
5月 15 23:37:14 gohi-pc bash[4279]: Example service started at 2020-05-15 23:37:14
5月 15 23:37:14 gohi-pc bash[4279]: HelloWorld...
5月 15 23:37:14 gohi-pc systemd[1]: helloworld.service: Succeeded.
3、最后将服务enable:
sudo systemctl enable helloworld
输出如下:
Created symlink /etc/systemd/system/multi-user.target.wants/helloworld.service → /etc/systemd/system/helloworld.service.