ite,my_open,my_release相应的函数体.
例如:
- static ssize_t my_open(struct inode *inode,struct file *file){
- static int counter=0;
- if(Device_Open)
- return -EBUSY;
- Device_Open ;
-
- sprintf(msg,"the device has been called %d timesn",counter );
- msg_ptr=msg;
- return 0;
- }
同时对于可卸载的内核模块(LKM),至少还有两个基本的模块:
例如本例中的:
- static int __init my_init(void){
- int result;
- result=register_chrdev(0,"sky_driver",&my_fops);
- if(result<0){
- printk("error:can not register the devicen");
- return -1;
- }
- if(my_major==0){
- my_major=result;
- printk("<1>hehe,the device has been registered!n");
- printk("<1>the virtual device was assigned major number %d.n",my_major);
- printk("<1>To talk to the driver,create a dev file withn");
- printk("<1>''mknod/dev/my c %d 0''n",my_major);
- printk("<1>Remove the dev and the file when donen");
- }
- return 0;
- }
-
- static void __exit my_exit(void){
- unregister_chrdev(my_major,"sky_driver");
- printk("<1>unloading the devicen");
- }
my_init 用于注册设备,获得设备的主设备号
调用register_chrdev(0,“sky_driver(设备名)”,&my_fops);
my_exit 用于注销设备
调用unregister_chrdev(my_major, “sky_driver(设备名)”);
然后在程序尾再调用这两个函数
Module_init(my_init);
Module_exit(my_exit)
MODULE_LICENSE(“GPL”);
编写自己的驱动程序源文件mydriver.c:
- #include <linux/kernel.h>
- #include <linux/module.h>
- #include <linux/fs.h>
- #include <linux/init.h>
- #include <linux/uaccess.h>
-
- #if CONFIG_MODVERSIONS == 1
- #define MODVERSIONS
- #include <linux/version.h>
- write(fd, &get, sizeof(get));
-
- read(fd, &buf, sizeof(buf));
- printf("The message changed to: %sn", buf);
- sleep(1);
- }
- else {
- printf("OMG...");
- return -1;
- }
-
- close(fd);
-
- return 0;
- }
gcc -o mydriver_test mydriver_test.c
./mydriver_test
输入任意字符串,驱动程序将字符串拷贝进新加入的设备,然后再读取出来,设备中保留字符串信息,再次输入将覆盖原来的信息.
ALL ended~~I will be back~~ 本文出自 “rangercyh的分享空间” 博客,请务必保留此出处http://rangercyh.blog.51cto.com/1444712/521244
|