I'm learning how to write character device drivers as dynamically-loadable modules for the Linux. Typically I use the following sequence of function calls to register the device and create a device file which appears under /dev/
:
alloc_chrdev_region(&first, 0, 1, "myclass");
myclass = class_create(THIS_MODULE, "myclass");
device_create(myclass, NULL, first, NULL, "mydevicefile");
cdev_init(&c_dev, &fops);
cdev_add(&c_dev, first, 1);
The device file then appears at /dev/mydevicefile
and I'm able to interact with it.
This made me wonder what would happen if passed an existing device file name instead of "mydevicefile":
device_create(myclass, NULL, first, NULL, "null");
This resulted in /dev/null
being replaced by my character device file -- and more concerning: an onslaught of error messages in my console from daemons expecting the original /dev/null
. Not even removing my faux null
module fixed this.
While in practice there should not be an existing device file with the same name as the one my module uses, the fact that it is theoretically possible to overwrite another device file still bothers me.
How do I protect against the case that a device file already exists with the same name as the one I intend to use?
UPDATE: I suppose what I'm really tying to find out is why udev is permitting the replacement.
Device node creation is typically left to be handled by user space operations. This is the purpose of udev
: to populate and handle the user space /dev/
directory by interpreting the data from sysfm
.
The name passed to the device_create
function is merely a suggested default name that appears in sysfm
along with other data about the device; it's ultimately up to the user space utility or user to decide what to do with that data.
It just happens that the default behavior of udev
when it encounters a device with the same name is to overwrite the old device node with the new device node: http://marc.info/?l=linux-hotplug&m=125559736630729