I have a C++ program that accesses USB pen drives/flash drives. It works for currently inserted flash drive. A normal C++ program doesn't execute until we run it. But I wanted the program to run automatically whenever a flash drive is inserted. How can I do that?
2 Answers
For general use, If you would like to run your program for any USB storage. Use the driver for the rule match.
Add a
udevrules filesudo nano /etc/udev/rules.d/90-detect-storage.rulesAdd this rule
ACTION=="add", DRIVERS=="usb-storage", DRIVER=="sd", RUN+="/pathto/yourprogram"If you want your program to distinguish the disks, so it runs different operations, use (you can pass its serial number or any attribute you like):
ACTION=="add", DRIVERS=="usb-storage", DRIVER=="sd", RUN+="/pathto/yourprogram $env{ID_VENDOR_ID} $env{ID_MODEL_ID}"Reload all rules
sudo udevadm control --reload-rulesUnplug and replug the flash drive
Notes:
I used this rule just to test which create a log when the rule is triggered:
ACTION=="add", DRIVERS=="usb-storage", DRIVER=="sd", RUN+="/bin/sh -c 'echo $env{ID_VENDOR_ID} $env{ID_MODEL_ID} >> /home/username/Desktop/usb-storage.log'"You can comment the rules you don't want by adding
#to the beginning of the line. Rules file can contain multiple rules.To check all the available
envvariables, use:ACTION=="add", DRIVERS=="usb-storage", RUN+="/bin/sh -c 'echo == >> /home/username/Desktop/usb-storage-env.log; env >> /home/username/Desktop/usb-storage-env.log'"To check for parameters to use for rule match, run:
sudo udevadm info --name=/dev/sdb1 --attribute-walk
References:
- Pass ATTR{idVendor} as argument in udev script
- Writing udev rules by Daniel Drake
- 48,105
-
2I like this approach, upvoting, congrats! – Frantique May 20 '15 at 06:27
-
2+150: Great answer: (AFAIK better than accepted) It makes a general rule for any USB device. In the acccepted answer the USB is restricted to a VID and a PID. – 0x2b3bfa0 May 23 '15 at 09:59
You can use udev to run an albitrary command. To make it work, create a rule in /etc/udev/rules.d/:
sudo nano /etc/udev/rules.d/my-usb-device.rules
And enter:
ACTION=="add", ATTRS{idProduct}=="XXXX", ATTRS{idVendor}=="YYYY", RUN+="/location/of/my/command"
NOTE: The XXXX and YYYY values will be taken from lsusb output.
- 8,493
-
I don't agree. The C++ program is a "command" after all. The user is asking for a solution to trigger that command. (He said: " But I wanted the program to run automatically whenever a flash drive is inserted. How could I do that?") – Frantique May 18 '15 at 13:51
-
For this[ http://ideone.com/uOReNj ] output of lsusb, what will be the values of
XXXXandYYYY? – vinayawsm May 18 '15 at 13:59 -
-
For letting my code trigger for every different pen drive, should I always update the "my-usb-device.rules" file? – vinayawsm May 18 '15 at 14:38
-
YOu have to create rule for every device. Or better refactor your C++ code to run as daemon and observe the udev triggers. – Frantique May 18 '15 at 14:39