ioctl是设备驱动程序中对设备的I/O通道进行管理的函数,程序可以通过ioctl向设备发送命令、参数配置等信息。file_operations结构中对应的ioctl接口如下:
- int (*ioctl) (struct inode *inode, struct file *filp,unsigned int cmd, unsigned long arg);
其中cmd是命令类型,arg是参数。
例1.5 字符设备ioctl实例
代码见光盘\src\1drivermodel\1-5ioctl。核心代码如下所示:
- //内核ioctl接口
- int simple_ioctl(struct inode *inode, struct file *filp,unsigned int cmd, unsigned long arg)
- {
- switch(cmd)
- {
- case COMMAND1:
- memset(demoBuffer,0x31,256);
- break;
- case COMMAND2:
- memset(demoBuffer,0x32,256);
- break;
- default:
- return -EFAULT;
- break;
- }
- return 0;
- }
- struct file_operations simple_fops = {
- .owner = THIS_MODULE,
- .ioctl = simple_ioctl,
- .open = simple_open,
- .release = simple_release,
- };
接下来编写一个应用程序,参考代码如下:
- #define COMMAND1 1
- #define COMMAND2 2
- void main(void)
- {
- int fd;
- int i;
- char data[256];
- int retval;
- fd=open("/dev/fgj",O_RDWR);
- if(fd==-1)
- {
- perror("error open\n");
- exit(-1);
- }
- printf("open /dev/fgj successfully\n");
- //应用层IOCTL控制
- retval=ioctl(fd,COMMAND1,0);
- if(retval==-1)
- {
- perror("ioctl error\n");
- exit(-1);
- }
- printf("send command1 successfully\n");
- retval=ioctl(fd,COMMAND2,0);
- if(retval==-1)
- {
- perror("ioctl error\n");
- exit(-1);
- }
- printf("send command1 successfully\n");
- close(fd);
- }
本例运行结果如下:
- [[email protected] /home]# insmod demo.ko
- [[email protected] /home]# mknod /dev/fgj c 224 0
- [[email protected] /home]# ./test
- open /dev/fgj successfully
- send command1 successfully
- send command1 successfully