一、开机执行一次的脚本
我们通过可以创建一个/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
- 完成上述操作,unmask 和enable 没有报错,但是这个服务不知道为什么没有自动运行起来导致。所以使用方法一开机自启的时候添加了下面的语句:
sudo systemctl start shixin.service
- 把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
如果想要编译成deb包的形式,可以参考代码:
https://download.csdn.net/download/sinat_22338935/90069624