您的位置:首页 > 其它

一个最简单的测试在dev/下生成字符设备的程序

2011-12-13 15:43 453 查看
先贴代码:

#include <linux/init.h> /* Needed for the macros */

#include <linux/kernel.h>

#include <linux/module.h> /* Needed for all modules */

#include <linux/fs.h>

#include <linux/cdev.h>

#include <linux/device.h>

MODULE_LICENSE("Dual BSD/GPL");

MODULE_AUTHOR("ttxgz");

int hello_major = 555;

int hello_minor = 0;

int number_of_devices = 1;

int memalloc_major = 111;

int memalloc_minor = 1;

struct cdev cdev;

dev_t dev = 0;

struct file_operations hello_fops = {

.owner = THIS_MODULE

};

struct class *my_class;

struct class *mem_class;

static int __init hello_init(void)

{

int result;

dev = MKDEV (hello_major, hello_minor);

/* create your own class under /sysfs */

my_class = class_create(THIS_MODULE, "my_class");

if(IS_ERR(my_class))

{

printk("Err: failed in creating class.\n");

return -1;

}

device_create( my_class, NULL, MKDEV(hello_major, hello_minor), NULL, "hello%d",0);

mem_class = class_create(THIS_MODULE, "mem_class");

device_create( mem_class, NULL, MKDEV(memalloc_major, memalloc_minor), NULL, "memalloc");

printk(KERN_ALERT "Hello, world!/n");

return 0;

}

static void __exit hello_exit(void)

{

dev_t devno = MKDEV (hello_major, hello_minor);

device_destroy(my_class, MKDEV(hello_major, 0)); //delete device node under /dev

class_destroy(my_class); //delete class created by us

unregister_chrdev_region (devno, number_of_devices);

devno = MKDEV(memalloc_major,memalloc_minor);

device_destroy(mem_class, MKDEV(memalloc_major, memalloc_minor)); //delete device node under /dev

class_destroy(mem_class); //delete class created by us

printk (KERN_INFO "char driver cleaned up\n");

printk(KERN_ALERT "Goodbye, cruel world/n");

}

module_init(hello_init);

module_exit(hello_exit);

Makefile:

ifeq ($(KERNELRELEASE),)

# Assume the source tree is where the running kernel was built

# You should set KERNELDIR in the environment if it's elsewhere

KERNELDIR ?= /lib/modules/$(shell uname -r)/build

# The current directory is passed to sub-makes as argument

PWD := $(shell pwd)

modules:

$(MAKE) -C $(KERNELDIR) M=$(PWD) modules

modules_install:

$(MAKE) -C $(KERNELDIR) M=$(PWD) modules_install

clean:

rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c .tmp_versions

.PHONY: modules modules_install clean

else

# called from kernel build system: just declare what our modules are

obj-m := hello.o

endif

直接在虚拟机下挂载,可以看见在dev下出现了hello0和memalloc两个设备,printk的信息可以通过dmesg | tail查看

上面的代码部分源于http://www.kerneltravel.net/?p=70http://www.embedu.org/Column/Column120.htm以及参考了http://www.360doc.com/content/11/0518/16/3038654_117697142.shtml
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐