KernelSpace
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#include <linux/init.h>
#include <linux/cdev.h>
#include <linux/mm.h>
#define DEMO_NAME "zhouhehe"
static dev_t dev;
static struct cdev *demo_cdev;
static signed count = 1;
static int zhouhehe_open(struct inode *inode, struct file *file)
{
int major = MAJOR(inode->i_rdev);
int minor = MINOR(inode->i_rdev);
printk("%s: major=%d, minor=%d\n",__func__,major,minor);
return 0;
}
static ssize_t zhouhehe_read(struct file *file, char __user *buf,size_t lbuf,loff_t *ppos)
{
printk("%s enter\n",__func__);
return 0;
}
static ssize_t zhouhehe_write(struct file *file, const char __user *buf,size_t count,loff_t *f_pos)
{
printk("%s enter\n",__func__);
return 0;
}
static const struct file_operations demodrv_fops = {
.owner = THIS_MODULE,
.open = zhouhehe_open,
.read = zhouhehe_read,
.write = zhouhehe_write
};
struct class *zhouhehe_class;
static int __init simple_char_init(void)
{
int ret;
printk("zhouhehe----simple_char_init\n");
ret = alloc_chrdev_region(&dev,0,count,DEMO_NAME);
if(ret)
{
printk("failed to allocate char device region\n");
return ret;
}
demo_cdev = cdev_alloc();
if(!demo_cdev)
{
printk("cdev_alloc failed\n");
goto unregister_chrdev;
}
cdev_init(demo_cdev,&demodrv_fops);
ret = cdev_add(demo_cdev,dev,count);
if(ret)
{
printk("cdev_add failed\n");
goto cdev_fail;
}
zhouhehe_class = class_create(THIS_MODULE,DEMO_NAME);
device_create(zhouhehe_class,NULL,dev,NULL,DEMO_NAME);
printk("successed register char device: %s\n",DEMO_NAME);
printk("Major number = %d,minor number = %d\n",MAJOR(dev),MINOR(dev));
return 0;
cdev_fail:
cdev_del(demo_cdev);
unregister_chrdev:
unregister_chrdev_region(dev,count);
return ret;
}
static void __exit simple_char_exit(void)
{
printk("removing device\n");
if(demo_cdev)
cdev_del(demo_cdev);
unregister_chrdev_region(dev,count);
}
module_init(simple_char_init);
module_exit(simple_char_exit);
MODULE_LICENSE("GPL");
Userspace
# include <stdio.h>
# include <fcntl.h>
# include <unistd.h>
#include <sys/mman.h>
#include <stdlib.h>
#define DEMO_DEV_NAME "/dev/zhouhehe"
int count = 0;
int parse_paras(int argc,char *argv[])
{
int ch;
opterr=0;
while((ch=getopt(argc,argv,"n:"))!=-1)
{
printf("optind:%d\n",optind);
printf("optarg:%s\n",optarg);
printf("ch:%c\n",ch);
switch(ch)
{
case 'n':
printf("option n:%s\n",optarg);
count = atoi(optarg);
printf("=====count=%d\n",count);
break;
default:
printf("Knowed option:%c\n",ch);
}
printf("optopt+%c\n",optopt);
}
return 0;
}
int main(int argc, char *argv[])
{
char buffer[64];
int fd;
int i = 0;
parse_paras(argc,argv);
printf("zhouhehe=============111111111\n");
for(i=0;i<count;i++)
{
printf("main[%d] start...\n",i);
fd = open(DEMO_DEV_NAME,O_RDONLY);
if(fd<0)
{
printf("open device %s failed\n",DEMO_DEV_NAME);
return -1;
}
printf("zhouhehe=============test[%d]\n",i);
read(fd,buffer,64);
close(fd);
}
free(paddr);
printf("main test done!!!\n");
return 0;
}
4590

被折叠的 条评论
为什么被折叠?



