I found a good code as example for a character device module : https://github.com/euspectre/kedr/blob/master/sources/examples/sample_target/cfake.c
I do not modified the code and I tested it. I obtained two devices (/dev/cfake0 and /dev/cfake1) but I would like to understand something.
There is two devices exported, but only one read function, how to specify which read function use for each device (if two read functions are implemented)?
In the end I would like to have two character devices (one for I2C communication, another one for SPI) on the same module, the module and user-space need the communication so I need to export both of them.
You have one function for each call on your file:
But all function have a struct file
as parameter.
This structure —which contains info about the file— is created by the module when it is loaded in the kernel. (see static int __init cfake_init_module(void);
function).
In the end I would like to have two character devices (one for I2C communication, another one for SPI)
You could have the stuff do to so :
In the example you gave, each file is created with a minor device number
(see cfake_construct_device()
). You could use this number to choose if the device is an SPI or an I2C device.
Your read
function could looks like:
ssize_t
cfake_read(struct file *filp, char __user *buf, size_t count,
loff_t *f_pos)
{
/* reading minor device number */
unsigned int mn = iminor(filp->f_inode);
/* select specialized function to use */
if (0 == mn)
return cfake_read_i2c(filp, buf, count, f_pos);
else
return cfake_read_spi(filp, buf, count, f_pos);
}
Said that, I do not think it's a good idea to have two different protocols in one module (unless the two device have to share data): on module crash, you will loose the two communication channels, and the module will be harded to debug.