You can mount your root fs read only, and switch between RO and RW.
For switching : I have 2 scripts in /usr/local/bin:
/usr/local/bin/rw with inside
#! /bin/sh
mount / -o rw,remount
/usr/local/bin/ro with
#! /bin/sh
mount / -o ro,remount
You then make them executable :
sudo chmod +x /usr/local/bin/ro /usr/local/bin/rw
Then you also have to change some config files :
/boot/cmdline.txt : add "ro" in the line so the system is mounted readonly at boot up
Some file are kept open when you start your system (that's why you can switch only once on the other answer). Mainly they are log files.
You can find which ones with :
fuser -v -m / 2>&1 | awk '($3 ~ /F.*/){ print "/proc/"$2"/fd"}' | xargs ls -l| grep '^l.w' | grep -v socket: | grep -v /dev/ | grep -v "/proc" | grep -v anon_inode | grep -v pipe
It is /var/log ! So one way is to change the link to a tmpfs, for example :
rm -rf /var/log
ln -s /run/log /var/log
- in your fstab file (/etc/fstab), you have to move some directory (temp,run) to ram memory : here is my fstab file :
/dev/mmcblk0p1 /boot vfat defaults 0 2
/dev/mmcblk0p2 / ext4 defaults,ro,noatime 0 1
proc /proc proc defaults 0 0
devpts /dev/pts devpts defaults,gid=5,mode=620,ptmxmode=0666 0 0
tmpfs /dev/shm tmpfs mode=0777 0 0
tmpfs /tmp tmpfs mode=1777 0 0
tmpfs /run tmpfs mode=0755,nosuid,nodev 0 0
sysfs /sys sysfs defaults 0 0
/dev/mmcblk0p3 /home/rpi vfat defaults,uid=1000,gid=1000 0 0
And finally, in that fstab, I mount my third partition as VFAT in /home/rpi
/dev/mmcblk0p3 /home/pi/Desktop/data vfat defaults,uid=1000,gid=1000 0 0
at the end of /etc/fstab to mount data folder as writable ? From your fstab I need to add "ro" also in /dev/mmcblk0p2 / ext4 defaults,ro,noatime 0 1 right? This way I prevent OS corrupting but could I damage the microSD by interrupting the power since I still have writable partitions? – Miky Dec 11 '18 at 22:21