在Linux中,可以使用udev(Linux设备管理器)来检测U盘的插入和拔出事件。udev是一个用于管理和监控设备的子系统,它可以通过监视内核事件来触发相应的操作。创建一个udev规则文件
10-usb.rules脚本如下
KERNEL=="sd[a-z]*",RUN+="/etc/udev/usb-hotplug.sh %k"
11-sd.rules脚本如下
KERNEL=="mmcblk[0-9]p[0-9]",RUN+="/etc/udev/sd-hotplug.sh %k"
sd-hotplug.sh脚本内容如下
#!/bin/sh
CONSOLE=/dev/ttyS0
dev=$1
mount_path=/tmp/sd
if [ $ACTION == "add" ]; then
if [ ! -d $mount_path ]; then
echo "+++sd add: $dev+++" > ${CONSOLE}
mkdir $mount_path
mount -t vfat /dev/$dev $mount_path
if [ $? != 0 ]; then
rmdir $mount_path
fi
fi
elif [ $ACTION == "remove" ]; then
if [ -d $mount_path ]; then
echo "---sd del: $dev---" > ${CONSOLE}
umount -l $mount_path
rmdir $mount_path
fi
fi
usb-hotplug.sh脚本内容如下
#!/bin/sh
CONSOLE=/dev/ttyS0
dev=$1
mount_path=/tmp/usb
if [ $ACTION == "add" ]; then
if [ ! -d $mount_path ]; then
echo "+++usb add: $dev+++" > ${CONSOLE}
if [ -e /dev/${dev}1 ]; then
part=1
fi
mkdir $mount_path
mount -t vfat /dev/$dev$part $mount_path
if [ $? != 0 ]; then
rmdir $mount_path
fi
fi
elif [ $ACTION == "remove" ]; then
if [ -d $mount_path ]; then
echo "---usb del: $dev---" > ${CONSOLE}
umount -l $mount_path
rmdir $mount_path
fi
fi