2012年10月9日 星期二

[udev][Embedded System] How to get USB device add/remove event from udev

In the following directory "/etc/udev/rules.d/", there are rule files for udev so you can add rules into rule files to call your application:

KERNEL=="sd*", ACTION=="add", RUN+="/usr/bin/my_program %k"
KERNEL=="sd*", ACTION=="remove", RUN+="/usr/bin/my_program %k"

1. KERNEL - Match against the kernel name for the device
2. ACTION - A environment variable to detect whether the device is being connected or disconnected. The value will be either "add" or "remove" respectively.

String substitutions
When writing rules which will potentially handle multiple similar devices, udev's printf-like string substitution operators are very useful. You can simply include these operators in any assignments your rule makes, and udev will evaluate them when they are executed.

The most common operators are %k and %n.

%k evaluates to the kernel name for the device, e.g. "sda3" for a device that would (by default) appear at /dev/sda3.

%n evaluates to the kernel number for the device (the partition number for storage devices), e.g. "3" for /dev/sda3.

String matching
As well as matching strings exactly, udev allows you to use shell-style pattern matching. There are 3 patterns supported:

* - match any character, zero or more times

? - match any character exactly once

[] - match any single character specified in the brackets, ranges are also permitted

P.S.
1. Rule files must have the .rules suffix.

2. Files in /etc/udev/rules.d/ are parsed in lexical order, and in some circumstances, the order in which rules are parsed is important. In general, you want your own rules to be parsed before the defaults, so I suggest you create a file at /etc/udev/rules.d/10-local.rules and write all your rules into this file.

For more information about udev rules, please visit http://reactivated.net/writing_udev_rules.html

Reference :

Related Posts:

0 意見:

張貼留言