When USB devices are connected in Linux the kernel assigns them a minor device number (i.e. the 0 in /dev/ttyUSB0). It seems that if I have a device at /dev/ttyUSB0, when I remove it and plug in a new USB device then new device will get a distinct device number. But if I wait long enough or add enough devices eventually one will be given device number 0. How does the kernel decide when to reuse device number 0?

For more context: I have a large number of USB devices connected to a server and I'm using the minor device number to track them. I want to detect when new devices are added and when old ones are removed. I'm worried that if new devices can get be assigned the same device number as an old device which has been removed then I won't know that the device has been replaced.


I'll half-answer my own question: I couldn't find any clear documentation of how device numbers are reused, but I did find a way to assign a more unique number to a device.

The trick is to use udev's IMPORT statement to generate a random number, for example this rule:

KERNEL=="ttyUSB*", IMPORT{program}="/bin/bash -c 'echo FOORAND=$RANDOM'", SYMLINK+="my-device-%n-%E{FOORAND}"

Will create symlinks to ttyUSB devices like /dev/my-device-0-3853. When a new device is added it will get a new random number.

The kernel number (%n) is included as well as the random number to ensure that the symlinks existing at any one time are always unique.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.