I need to do some actions when a specific USB device is removed/added. I need a fast response on the order of milli-seconds.
How can I do this in a shell script?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityI need to do some actions when a specific USB device is removed/added. I need a fast response on the order of milli-seconds.
How can I do this in a shell script?
Assuming you are using a Linux distribution with udev support and you have root/administrator access to it then you can use udev rules to trigger on specific operations.
If the following example is added to a /etc/udev/rules.d/example.rules then it will run the specified script when a block device is added with the specified parameters.
ACTION=="add", SUBSYSTEM=="block", ATTRS{manufacturer}=="HitachiGST", ATTRS{serial}=="31001206110000000000", RUN+="/a/script/to/run.sh"
That particular rule executes when my USB harddrive is inserted and attaches to the block system. It is quite easy to tweak the rules to match a specific lowlevel USB event.
I found the Debian UDEV wiki page and Writing Udev Rules site to be very helpful in getting the right rules for my situation.
As an initial answer you could listen for changes in the file /proc/bus/input/devices
and check for USB entries
. With this you can avoid polling the device. Or you can perform a loop polling when the device is inserted.
Probably shell script won't be as fast as you want. Would be better to use another script language Python
or C/C++
.
http://libusb.sourceforge.net/doc/examples-code.html http://sourceforge.net/apps/trac/pyusb/