⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 hello.c

📁 刚学LINUX驱动模块时写的一个测试程序
💻 C
字号:
#include <linux/module.h>#include <linux/config.h>#include <linux/init.h>#include <linux/fs.h>#include <linux/errno.h>#include <linux/kernel.h>#include <asm/uaccess.h>#define MAJOR_NUM 125#define DEVICE_NAME "char_dev"
#define BUF_LEN 10#define IOCTL_SET_MSG _IOR(MAJOR_NUM, 0, int*)
#define IOCTL_GET_MSG _IOR(MAJOR_NUM, 1, int*)static Device_Open=0;static char *Message_Ptr;static char Message[BUF_LEN];static int flags=0xff;static int device_open(struct inode *inode, struct file *file){  printk("Device Open\n");  if (Device_Open) return -EBUSY;  Device_Open++;    //MOD_INC_USE_COUNT;  Message_Ptr = Message;  return 0;}static int device_release(struct inode *inode, struct file *file){  printk("Device release\n");  Device_Open--;   return 0;}static ssize_t device_write(struct file *file,const char *buffer,size_t length,loff_t *offset){  int value;  int bytes_writes=10;  int *data=(int*)buffer;   char str[256];      get_user(value,data);   flags=value;   sprintf(str,"device write %d\n",flags);   printk((str));  return bytes_writes;}static ssize_t device_read(struct file *file,char *buffer,size_t length,loff_t *offset){  int bytes_read=10;  int *data=(int *)buffer;  char str[256];  sprintf(str,"device_read %d\n",flags);  printk((str));    put_user(flags,data);  return bytes_read;}int device_ioctl(struct inode *inode,                 struct file *file,                 unsigned int ioctl_num,/* The number of the ioctl */                 unsigned long ioctl_param) /* The parameter to it */{  int	temp;  int *data;  int   ioctl;  char  str[256];  printk(("Device_ioctl\n"));    switch (ioctl_num)   {    case IOCTL_SET_MSG:           data = (int*) ioctl_param;            get_user(temp, data);      sprintf(str, "Device_ioctl SET_MSG %d\n", temp);      printk((str));            break;    case IOCTL_GET_MSG:          printk(("Device_ioctl PUT_MSG\n"));      break;  }  return 0;};static struct file_operations Fops={.owner=THIS_MODULE,.read=device_read,.write=device_write,.open=device_open,.release=device_release,.ioctl=device_ioctl,};static int test_init(void){   int ret_val;	   ret_val=register_chrdev(MAJOR_NUM,DEVICE_NAME,&Fops);     if(ret_val<0){       printk("<0>register failure with %d\n","num",ret_val);       return ret_val;      } printk ("<0>%s The major device number is %d.\n",          "Registeration is a success",MAJOR_NUM); printk("<0>Module ok! \n"); return 0;}static void test_clear(void){int ret; printk("<0>Goodbye!\n");ret=unregister_chrdev(MAJOR_NUM,DEVICE_NAME);if(ret<0)printk("Error unregister:%d\n",ret);}MODULE_LICENSE("GPL-huming");module_init(test_init);module_exit(test_clear);

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -