LDD3中第三章讲解的scull驱动程序中的头文件“Scull.h”有下面这么一段话,现在我给出其具体的解析。
/*
* Ioctl definitions
*/
/* Use 'k' as magic number */
#define SCULL_IOC_MAGIC 'k'
这里的k值是实现需要自己确定,用来标识本命令,是一个八位的二进制,例如选取0x0a。
/* Please use a different 8-bit number in your code */
#define SCULL_IOCRESET _IO(SCULL_IOC_MAGIC, 0)
首先生成一个无参数的命令编号,根据
#define _IO(type,nr) _IOC(_IOC_NONE,(type),(nr),0)
可以得到生成的编号为:00 00000000000000 00001010 00000000, 生成结果就是SCULL_IOCRESET等于该编号值。
/*
* S means "Set" through a ptr,
* T means "Tell" directly with the argument value
* G means "Get": reply by setting through a pointer
* Q means "Query": response is on the return value
* X means "eXchange": switch G and S atomically
* H means "sHift": switch T and Q atomically
*/
#define SCULL_IOCSQUANTUM _IOW(SCULL_IOC_MAGIC, 1, int)
根据:#define _IOW(type,nr,size) _IOC(_IOC_WRITE,(type),(nr),sizeof(size))
生成写的命令编号:01 00000000100000 00001010 00000001
#define SCULL_IOCSQSET _IOW(SCULL_IOC_MAGIC, 2, int)
生成写的命令编号:01 00000000100000 00001010 00000010
#define SCULL_IOCTQUANTUM _IO(SCULL_IOC_MAGIC, 3)
生成的命令编号:00 00000000000000 00001010 00000011
#define SCULL_IOCTQSET _IO(SCULL_IOC_MAGIC, 4)
生成的命令编号:00 00000000000000 00001010 00000100
#define SCULL_IOCGQUANTUM _IOR(SCULL_IOC_MAGIC, 5, int)
生成读的命令编号:10 00000000100000 00001010 00000101
#define SCULL_IOCGQSET _IOR(SCULL_IOC_MAGIC, 6, int)
生成读的命令编号:10 00000000100000 00001010 00000110
#define SCULL_IOCQQUANTUM _IO(SCULL_IOC_MAGIC, 7)
生成的命令编号:00 00000000000000 00001010 00000111
#define SCULL_IOCQQSET _IO(SCULL_IOC_MAGIC, 8)
生成的命令编号:00 00000000000000 00001010 00001000
#define SCULL_IOCXQUANTUM _IOWR(SCULL_IOC_MAGIC, 9, int)
生成读写的命令编号:11 00000000100000 00001010 00001001
#define SCULL_IOCXQSET _IOWR(SCULL_IOC_MAGIC,10, int)
生成读写的命令编号:11 00000000100000 00001010 00001010
#define SCULL_IOCHQUANTUM _IO(SCULL_IOC_MAGIC, 11)
生成的命令编号:00 00000000100000 00001010 00001011
#define SCULL_IOCHQSET _IO(SCULL_IOC_MAGIC, 12)
生成的命令编号:00 00000000100000 00001010 00001100
/*
* The other entities only have "Tell" and "Query", because they're
* not printed in the book, and there's no need to have all six.
* (The previous stuff was only there to show different ways to do it.
*/
#define SCULL_P_IOCTSIZE _IO(SCULL_IOC_MAGIC, 13)
生成的命令编号:00 00000000100000 00001010 00001101
#define SCULL_P_IOCQSIZE _IO(SCULL_IOC_MAGIC, 14)
生成的命令编号:00 00000000100000 00001010 00001110
那么这些编号值有什么用呢,我们在“Main.c”文件中找到了函数ioctl的具体实现,里面根据传过来的cmd的数值不同(这里cmd的值都对应着一个编号值)而执行不同的操作。