app&驱动程序数据传输,自动创建设备节点

99 阅读1分钟

获取app数据

copy_to_user(buf, hello_buf, len)

static unsigned char hello_buf[100];
static ssize_t hello_read(struct file * file, char __user *buf, size_t size, loff_t *offset) 
{
  unsigned long len = size > 100 ? 100 : size;
  // 获取app输入的内容
  if (copy_to_user(buf, hello_buf, len))
  {
    printk("copy_to_user use failed\n");
    return -1;
  }
  printk("%s %s %d\n", __FILE__, __FUNCTION__, __LINE__);
  return size;
}

向app发送数

copy_from_user(hello_buf, buf, len)

static unsigned char hello_buf[100];
static ssize_t hello_write(struct file * file, const char __user *buf, size_t size, loff_t *offset) 
{
  unsigned long len = size > 100 ? 100 : size;
  // 给app传送内容
  if (copy_from_user(hello_buf, buf, len))
  {
    printk("copy_from_user use failed\n");
    return -1;
  }
  printk("%s %s %d\n", __FILE__, __FUNCTION__, __LINE__);
  return size;
}

入口函数创建class目录

hello_class = class_create(THIS_MODULE, "hello_class");

入口函数创建设备节点

device_create(hello_class, NULL, MKDEV(major, 0), NULL, "hello");

// 2.注册chrdev 3.入口函数
static int hello_init(void)
{
  major = register_chrdev(0, "100ask.net", &hello_drv);
  // 创建目录
  hello_class = class_create(THIS_MODULE, "hello_class");
  if (IS_ERR(hello_class))
  {
    printk("failed to allocate class\n");
    return PTR_ERR(hello_class);
  }
  // 创建设备节点,相当于创建文件
  device_create(hello_class, NULL, MKDEV(major, 0), NULL, "hello");
  return 0;
}

查看创建设备节点结果

ls /dev/hello image.png

出口函数删除设备节点

device_destroy(hello_class, MKDEV(major, 0));

出口函数删除class目录

class_destroy(hello_class);

//  3.出口函数
static void hello_exit(void)
{
  // 删除文件(设备节点)
  device_destroy(hello_class, MKDEV(major, 0));
  // 删除目录
  class_destroy(hello_class);
  unregister_chrdev(major, "100ask.net");
};

app使用驱动的4种方式

1、连续进入房间看看孩子状态>查询方式

2、陪小孩一块睡觉 -> 休眠-唤醒

3、妈妈很多干活,中途陪小孩睡一会 -> poll方式

4、妈妈在客厅干活,小孩醒了告诉妈妈-> 异步通知