学无先后,达者为师

网站首页 编程语言 正文

systemd开机启动和关机回调脚本

作者:小坚学Linux 更新时间: 2022-07-09 编程语言

一、开机执行一次的脚本
我们通过可以创建一个/etc/rc.local文件:
/etc/rc.local文件内容如下:

#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.

bash /opt/reboot.sh &

exit 0

这样子我们的linux系统每次开机都会运行一次/opt/reboot.sh脚本。

一、开机自动运行的systemd服务
touch.service:

[Unit]
Description=touch service

[Service]
Type=oneshot

ExecStart=touch /jian
#ExecStop=rm /jian
PrivateTmp=true

[Install]
WantedBy=multi-user.target
Alias=touch.service

把这个文件放到/lib/systemd/system/目录,然后执行命令使能它,让他开机自动运行一次:

sudo systemctl enable touch.service

同时我们可以手动运行这个服务:

sudo systemctl start touch.service

二、关机执行systemd服务
rtc_load.service:

[Unit]
Description=set the RTC from the system time
Before=systemd-poweroff.service systemd-reboot.service systemd-halt.service
DefaultDependencies=no
 
[Service]
ExecStart=hwclock -w
Type=forking
 
[Install]
WantedBy=poweroff.target
WantedBy=reboot.target
WantedBy=halt.target

把这个文件放到/lib/systemd/system/目录,然后使用以下命令创建几个软连接:

ln -s /lib/systemd/system/rtc_load.service /usr/lib/systemd/system/halt.target.wants/
ln -s /lib/systemd/system/rtc_load.service /usr/lib/systemd/system/poweroff.target.wants/
ln -s /lib/systemd/system/rtc_load.service /usr/lib/systemd/system/reboot.target.wants/

原文链接:https://blog.csdn.net/sinat_22338935/article/details/125596100

栏目分类
最近更新