一、开机执行一次的脚本
我们通过可以创建一个/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/
三、关机执行systemd服务
不知道为什么上面的关机服务不行了,使用下面的方法把。
.service
文件以定义服务,例如 shixin.service
。sudo gedit /etc/systemd/system/shixin.service
[Unit]
Description=shixin service
After=network.target
[Service]
Type=oneshot
RemainAfterExit=true
ExecStart=/bin/true
ExecStop=/usr/sbin/shixin_uart_send
[Install]
WantedBy=shutdown.target
Unit
部分,我们描述了服务的名称和其依赖关系。此处添加的依赖关系是 network.target
,它表示此服务需要在网络启动后才开始运行。Service
部分,我们设置服务的某些信息:
Type
设置为 oneshot
。这意味着服务只运行一次并在完成后退出。RemainAfterExit
设置为 true
。这将使 systemd 记录服务状态并在启动时更新系统状态。ExecStart
中,我们简单地使用 /bin/true
命令来表示该服务不需要运行命令。ExecStop
中,我们指定了要在系统关机时运行的脚本路径。您应该将 /usr/sbin/shixin_uart_send
更改为自己的脚本路径。Install
部分,我们将服务添加到 shutdown.target
中,表明该服务只在系统关机时运行。systemd
守护进程并启用新服务:sudo systemctl daemon-reload
sudo systemctl unmask shixin.service
sudo systemctl enable shixin.service
sudo systemctl start shixin.service
[Unit]
Description=shixin service
#After=network.target
[Service]
Type=oneshot
RemainAfterExit=true
ExecStart=/bin/true
ExecStop=/usr/sbin/shixin_uart_send
[Install]
#WantedBy=shutdown.target
WantedBy=multi-user.target