1. Driver Source Code
#include
#include
#include
#include
#include
MODULE_LICENSE("GPL");
#define MAJOR_NUM 254
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");
}
else
{
printk("globalvar register sucess");
}
return ret;
}
static void __exit globalvar_exit(void)
{
int ret;
ret=unregister_chrdev(MAJOR_NUM,"globalvar");
if(ret)
{
printk("globalvar unregister failure");
}
else
{
printk("globalvar unregister sucess");
}
}
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);
}
module_init(globalvar_init);
module_exit(globalvar_exit);
================================================Driver Source Code Ends
2. App source code
#include
#include
#include
#include
main()
{
int fd,num1,num2;
fd = open("/dev/chrdev",O_RDWR,S_IRUSR | S_IWUSR);
if(fd!=-1)
{
read(fd,&num,sizeof(int));
printf("the globalvar is %d",num);
printf("please input the num written to globalvar");
scanf("%d",&num1);
write(fd,&num1,sizeof(int));
read(fd,&num2,sizeof(int));
printf("the globalvar is %d",num2);
close(fd);
}
else
{
printf("device open failure");
}
}
App can be compiled by command: gcc -o chrdevapp chrdevApp.c
=========================================================App source code end
3. This Module can be compile in Linux 2.4 kernel(Red Hat 9.0). With tool GCC
the command is:
gcc -DMODULE -D__KERNLE__ -I /usr/src/linux-2.4.20-8/include -c chrdev.c
Then, there will be a module file chrdev.o
==> Use command: insmod chrdev, to add this module to kernel, this command will call register_chrdev() method to register this module to kernel. if sucessful, check /proc/modules, chrdev module will show there.
==> the resource that driver declare can be released when this module is removed by command: rmmod chrdev, this command will call unregister_chrdev() method.
==>We must use the command: insmod chrdev.o to add this module to kernel, then run the App. If not, when run app, it will show "Device open error"
阅读(751) | 评论(0) | 转发(0) |