一个简单的字符程序

clude<linux/module.h>
#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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值