#include<linux/init.h>
#include<linux/fs.h>
#include<asm/uaccess.h>
MODULE_LICENSE("GPL");
#define MAJOR_NUM 256
static ssize_t globalvar_read(struct file *,char *, size_t ,loff_t*);
static ssize_t globalvar_write(struct file *,const char*,size_t,loff_t*);
struct file_operations globalvar_fops ={read:globalvar_read,write:globalvar_write,};
static int global_var = 0;
static int __init globalvar_init(void){
int ret;
ret=register_chrdev(MAJOR_NUM,"globalvar",&globalvar_fops);
if(ret) printk("globalvar register failure!\n");
else printk("globalvar register success!\n");
return ret;
}
static void __exit globalvar_exit(void){
// int ret;
unregister_chrdev(MAJOR_NUM,"globalvar");
//if(ret) printk("globalvar unregister failure!\n");
//else printk("globalvar unregister success!\n");
}
static ssize_t globalvar_read(struct file *filp,char *buf, size_t len,loff_t* off)
{
if(copy_to_user(buf,&global_var,sizeof(int))) return -EFAULT;
return sizeof(int);
}
static ssize_t globalvar_write(struct file *filp,const char *buf, size_t len,loff_t* off)
{
if(copy_from_user(&global_var,buf,sizeof(int))) return -EFAULT;
return sizeof(int);
}
创建一个字符设备
mknod /dev/globalvar c 256 0
安装驱动模块
insmod global.ko
测试程序:
#include<sys/types.h>
#include<sys/stat.h>
#include<stdio.h>
#include<fcntl.h>
int main(){
int fd,num;
//open the char device
fd = open("/dev/globalvar",O_RDWR,S_IRUSR | S_IWUSR);
if(fd != -1){
read(fd,&num,sizeof(int));//read the fd to the num count is sizeof(int)
printf(" The globalvar is %d \n",num);
printf("Please input the num written to globalvar\n");
scanf("%d",&num);
write(fd,&num,sizeof(int));//write the num to the fd
read(fd,&num,sizeof(int));
printf(" The globalvar is %d \n",num);
close(fd);
}
else
{
printf("Device open failure\n");
}
return 0;
}
Makefile:
obj-m :=global.o
KERNEL_DIR:=/lib/modules/$(shell uname -r)/build
PWD:=$(shell pwd)
all:
make -C $(KERNEL_DIR) M=`pwd` modules
# make -C $(KERNEL_DIR) SUBDIRS=$(PWD) modules
clean:
-rm -rf *.o *.ko *.mod.o