树莓派直接断电可能会导致SD分区损坏,从而导致无法正常开机,如果修复失败就只能重新刷系统,希望你对系统做了备份…

SD卡本身不适合长时间读写操作,正常情况下到了一定时间都可能会发生数据读写错误。

一个避免上述问题的方法是把系统设置为只读系统,这样就不会在突然断电的情况下导致系统出现错误。


参考链接:Protect your Raspberry PI SD card, use Read-Only filesystem

参考链接:How to make your Raspberry Pi file system read-only (Raspbian Stretch)

# 更新软件包并重启
sudo apt update; sudo apt upgrade
sudo apt reboot

# 删除不需要的软件
sudo apt remove --purge wolfram-engine triggerhappy anacron logrotate dphys-swapfile xserver-common lightdm
sudo apt autoremove --purge

# 关闭服务
sudo systemctl disable x11-common
sudo systemctl disable bootlogs
sudo systemctl disable console-setup

更换日志管理

sudo apt install busybox-syslogd
sudo dpkg --purge rsyslog

取消swap分区,并设置为read-only

sudo vim /boot/cmdline.txt

# 增加三个单词
# console=serial0,115200 console=tty1 root=PARTUUID=393effb4-02 rootfstype=ext4 elevator=deadline fsck.repair=yes rootwait fastboot noswap ro
fastboot noswap ro

将一些系统文件移到临时文件系统

sudo rm -rf /var/lib/dhcp /var/lib/dhcpcd5 /var/run /var/spool /var/lock /etc/resolv.conf
sudo ln -s /tmp /var/lib/dhcp
sudo ln -s /tmp /var/lib/dhcpcd5
sudo ln -s /tmp /var/run
sudo ln -s /tmp /var/spool
sudo ln -s /tmp /var/lock

sudo touch /tmp/dhcpcd.resolv.conf
sudo ln -s /tmp/dhcpcd.resolv.conf /etc/resolv.conf

修改文件

sudo vim /etc/systemd/system/dhcpcd5.service

# PIDFile=/var/run/dhcpcd.pid
PIDFile=/var/run/dhcpcd.pid

更改系统随机种子

sudo rm /var/lib/systemd/random-seed
sudo ln -s /tmp/random-seed /var/lib/systemd/random-seed


sudo vim /lib/systemd/system/systemd-random-seed.service

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStartPre=/bin/echo "" >/tmp/random-seed # 新增
ExecStart=/lib/systemd/systemd-random-seed load
ExecStop=/lib/systemd/systemd-random-seed save

sudo systemctl daemon-reload

修改文件系统为read-only

sudo vim /etc/fstab


tmpfs           /tmp            tmpfs   nosuid,nodev         0       0
tmpfs           /var/log        tmpfs   nosuid,nodev         0       0
tmpfs           /var/tmp        tmpfs   nosuid,nodev         0       0

切换RO模式和RW模式

image-20201210205854363

sudo vim /etc/bash.bashrc

set_bash_prompt() {

fs_mode=$(mount | sed -n -e "s/^\/dev\/.* on \/ .*(\(r[w|o]\).*/\1/p")

PS1='\[\033[01;32m\]\u@\h${fs_mode:+($fs_mode)}\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '

}

alias ro='sudo mount -o remount,ro / ; sudo mount -o remount,ro /boot'

alias rw='sudo mount -o remount,rw / ; sudo mount -o remount,rw /boot'

PROMPT_COMMAND=set_bash_prompt
sudo vim /etc/bash.bash_logout

mount -o remount,ro /
mount -o remount,ro /boot

重启

sudo reboot

如果出现这样的错误,可能是/tmp的权限问题。

image-20201210205056610

sudo /etc/profile.d/chmod_tmp.sh

# 添加这一行
sudo chmod 777 /tmp