usb和sdcard的自动挂载规则是在/etc/udev/rules.d/目录下,

u盘自动挂载规则

/etc/udev/rules.d/11-usb-mount.rules
KERNEL!="sd[a-z][0-9]",GOTO="automount_exit"
ACTION=="add", SUBSYSTEMS=="usb", SUBSYSTEM=="block",RUN+="/bin/mkdir /mnt/usb",RUN+="/usr/bin/systemd-mount --no-block --automount=yes $devnode /mnt/usb"
ACTION=="remove", RUN+="/usr/bin/systemd-umount /mnt/usb",RUN+="/bin/rmdir  /mnt/usb"
LABEL="automount_exit"

sdcard自动挂载规则

/etc/udev/rules.d/11-sd-mount.rules
KERNEL!="mmcblk0p1",GOTO="automount_exit"
ACTION=="add", SUBSYSTEM=="block",RUN+="/bin/mkdir /mnt/sd",RUN+="/usr/bin/systemd-mount --no-block --automount=yes $devnode /mnt/sd"
ACTION=="remove", RUN+="/usr/bin/systemd-umount /mnt/sd",RUN+="/bin/rmdir /mnt/sd"
LABEL="automount_exit"


udev规则可参考udev文档说明:

https://www.freedesktop.org/software/systemd/man/udev.html

systemd-mount的用法请参考:

https://www.freedesktop.org/software/systemd/man/systemd-mount.html

以上例子中的udev规则中匹配sd[a-z][0-9]的设备, 当系统中检查usb设备插入时, 就会执行add中的操作, 当检查到usb设备拔出后, 就会执行remove中的操作. 

udev规则定义完成后, 需要重新导入udev规则

udevadm control --reload-rules

规则中的remove操作是在拔出U盘后执行的, 为了保证写入U盘的数据不丢失, 在拔出U盘之前需要执行sync命令把数据写入U盘中.


在挂载可移动设备时, 不要在udev规则中调用mount命令.

具体原因参考以下内容说明:

https://wiki.archlinux.org/index.php/Udev

Mounting drives in rules

To mount removable drives, do not call mount from udev rules. This is ill-advised for two reasons: (1) systemd by default runs systemd-udevd.servicewith a separate "mount namespace" (see namespaces(7)), which means that mounts will not be visible to the rest of the system. (2) Even if you change the service parameters to fix this (commenting out the PrivateMounts and MountFlags lines), there is another problem which is that processes started from Udev are killed after a few seconds. In case of FUSE filesystems, such as exFAT (which is common to find on mp3 players or shareable thumb drives) and NTFS, "mount" starts a user-space process to handle the filesystem internals; when this is killed you will get Transport endpoint not connected errors if you try to access the filesystem.

There are some options that work:

  • Start a custom systemd service from the Udev rule; the systemd service can invoke a script which can start any number of long-running processes (like FUSE). A concise example which automatically mounts USB disks under /media is udev-media-automount. It was found to be fast and reliable. A variant of the same idea is explained in this blog post.
  • Use systemd-mount instead of mount in your Udev rule. This is recommended by systemd developers. For example this Udev rule should mount USB disks under "/media":





  • No labels