How to execute C++ program whenever a USB flash drive is inserted

For general use, If you would like to run your program for any USB storage. Use the driver for the rule match.

  1. Add a udev rules file

    sudo nano /etc/udev/rules.d/90-detect-storage.rules
    
  2. Add 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}"
    
  3. Reload all rules

    sudo udevadm control --reload-rules
    
  4. Unplug 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 env variables, 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

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.