笔者以前使用service命令,现在切换到Linux系统最新的初始化系统systemd(system daemon),需要自定义service服务然后设置开机启动。相比于/etc.init.d下(SysV)的脚本启动,Systemd的service可以灵活的控制什么时候要启动服务,配置开机启动更加方便。
1、在/home/mycentos目录下新建一个程序 while_date.sh
#!/usr/bin/bash
while true
do
echo `date`,"ok" >> /home/mycentos/while_date.log
sleep 5s
done
2、在/usr/lib/systemd/system目录下新建while_date.service
service文件一般由:[Unit]、[Service]和[Install] 三部分组成。以 ".service" 为后缀的单元文件, 封装了一个被 systemd 监视与控制的进程。
[Unit]: unit 本身的说明,以及与其他相依 daemon 的设置;
[Service]:定义服务的具体管理和操作方法。
[Install]:是将此 unit 安装到哪个 target (运行级别)里面。这个设置非常重要,因为执行systemctl enable while_date.service命令时,while_date.service的符号链接,就会放在/etc/systemd/system目录下面的multi-user.target.wants子目录之中。
[Unit]
Description=mytest:while date service
After=network.target sshd.service
[Service]
#Type=forking
PIDFile=/tmp/mxy.pid
ExecStartPre=/usr/bin/rm -f /tmp/mxy.pid
ExecStart= /home/mycentos/while_date.sh
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=process
PrivateTmp=true
[Install]
WantedBy=multi-user.target
3、 systemctl enable设置开机启动
设置开机启动会在/etc/systemd/system/multi-user.target.wants/目录下新建一个/usr/lib/systemd/system/while_date.service 文件的链接。

在/etc/systemd/system/multi-user.target.wants/目录下可以看到这个链接文件。

4、添加或修改配置文件后,需要重新加载
systemctl daemon-reload
5、重启测试成功

在实践中有个小问题就是,重启后又这个进程,但是没有 while_date.log文件,手动拉起是正常的,后面得到笔者的centos的bash是在/usr/bin/bash ,而不是/bin/bash,在while_date.sh中修改后正常。
systemctl disable禁止开机启动后会移除symlink链接。

systemd命令总结:
手动启动服务:systemctl start while_date.service
手动停止服务:systemctl stop while_date.service
查看服务状态: systemctl status while_date.service

查看进程启动的时间:systemd-analyze blame | grep while_date.service

查看进程是否开机启动:systemctl is-enabled while_date.service
杀死服务:systemctl kill while_date.service
网友评论