Udev rules

From thelinuxwiki
Jump to: navigation, search

udev rules are flexible and very powerful. Here are some of the things you can use rules to achieve:

  • Rename a device node from the default name to something else
  • Provide an alternative/persistent name for a device node by creating a symbolic link to the default device node
  • Name a device node based on the output of a program
  • Change permissions and ownership of a device node
  • Launch a script when a device node is created or deleted (typically when a device is attached or unplugged)
  • Rename network interfaces


Contents

rules dir

/etc/udev/rules.d/


rules file name

(to be parsed before default rules)
 10-local.rules


Gathering device info

example for /dev/sdc

udevadm info -a -p  $(udevadm info -q path -n /dev/sdc)|grep -E "device|parent|KERNEL|SUBSYSTEMS|model"

example rules

usb hard drive

KERNEL=="sd*", SUBSYSTEMS=="scsi", ATTRS{model}=="External USB HDD", SYMLINK+="usbhd%n"

testing the rules

Assuming you are on a recent kernel with inotify support, udev will automatically monitor your rules directory and automatically pick up any modifications you make to the rule files.

to check you kernel...

# cat /etc/kernkels/kernel-name |grep INOTIFY
   CONFIG_INOTIFY_USER=y

To test with inotify support... first we must make the rules take effect

If the device is removable, then disconnect and reconnect

or

if non-removable you can run

 # udevadm trigger

if your kernel does not have inotify support, new rules will not be detected automatically. In this situation, you must run

 # udevadm control --reload-rules

Next we can view the symbolic links get created dymically

Example with cellphone plugged first, ext usb HD plugged in second...

# ls /dev/sd*
/dev/sda   /dev/sda2  /dev/sda5  /dev/sdb1  /dev/sdc  /dev/sdd1
/dev/sda1  /dev/sda4  /dev/sdb   /dev/sdb2  /dev/sdd  /dev/sdd2


# ls -l /dev/usbh*
lrwxrwxrwx 1 root root 3 Jan 25 23:44 /dev/usbhd -> sdd
lrwxrwxrwx 1 root root 4 Jan 25 23:44 /dev/usbhd1 -> sdd1
lrwxrwxrwx 1 root root 4 Jan 25 23:44 /dev/usbhd2 -> sdd2

unplugged both devices, then plugged in usb HD , note the symlinks correctly point to the new device labels

# ls -l /dev/usbh*
lrwxrwxrwx 1 root root 3 Jan 25 23:49 /dev/usbhd -> sdc
lrwxrwxrwx 1 root root 4 Jan 25 23:49 /dev/usbhd1 -> sdc1
lrwxrwxrwx 1 root root 4 Jan 25 23:49 /dev/usbhd2 -> sdc2


Links:

http://www.gentoo.org/doc/en/udev-guide.xml
http://www.reactivated.net/writing_udev_rules.html#example-usbhdd