一,ioctl使用实例
驱动程序.h文件 memdev.h
[cpp] view plaincopy
- /* 定义幻数 */
- #define MEMDEV_IOC_MAGIC ‘k‘
- /* 定义命令 */
- #define MEMDEV_IOCPRINT _IO(MEMDEV_IOC_MAGIC, 1)
- #define MEMDEV_IOCGETDATA _IOR(MEMDEV_IOC_MAGIC, 2, int)
- #define MEMDEV_IOCSETDATA _IOW(MEMDEV_IOC_MAGIC, 3, int)
- #define MEMDEV_IOC_MAXNR 3
驱动程序.c文件
[cpp] view plaincopy
- /*IO操作*/
- int memdev_ioctl(struct inode *inode, struct file *filp,
- unsigned int cmd, unsigned long arg)
- {
- int err = 0;
- int ret = 0;
- int ioarg = 0;
- /* 检测命令的有效性 */
- if (_IOC_TYPE(cmd) != MEMDEV_IOC_MAGIC)
- return -EINVAL;
- if (_IOC_NR(cmd) > MEMDEV_IOC_MAXNR)
- return -EINVAL;
- /* 根据命令类型,检测参数空间是否可以访问 */
- if (_IOC_DIR(cmd) & _IOC_READ)
- err = !access_ok(VERIFY_WRITE, (void *)arg, _IOC_SIZE(cmd));
- else if (_IOC_DIR(cmd) & _IOC_WRITE)
- err = !access_ok(VERIFY_READ, (void *)arg, _IOC_SIZE(cmd));
- if (err)
- return -EFAULT;
- /* 根据命令,执行相应的操作 */
- switch(cmd) {
- /* 打印当前设备信息 */
- case MEMDEV_IOCPRINT:
- printk("<--- CMD MEMDEV_IOCPRINT Done--->\n\n");
- break;
- /* 获取参数 */
- case MEMDEV_IOCGETDATA:
- ioarg = 1101;
- ret = __put_user(ioarg, (int *)arg);
- break;
- /* 设置参数 */
- case MEMDEV_IOCSETDATA:
- ret = __get_user(ioarg, (int *)arg);
- printk("<--- In Kernel MEMDEV_IOCSETDATA ioarg = %d --->\n\n",ioarg);
- break;
- default:
- return -EINVAL;
- }
- return ret;
- }
应用程序
[cpp] view plaincopy
- #include "memdev.h"
- cmd = MEMDEV_IOCPRINT;
- if (ioctl(fd, cmd, &arg) < 0)
- {
- printf("Call cmd MEMDEV_IOCPRINT fail\n");
- return -1;
- }
- cmd = MEMDEV_IOCSETDATA;
- arg = 2007;
- if (ioctl(fd, cmd, &arg) < 0)
- {
- printf("Call cmd MEMDEV_IOCSETDATA fail\n");
- return -1;
- }
时间: 2025-01-09 03:59:34