生活随笔
收集整理的這篇文章主要介紹了
LInux 字符设备驱动程序
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
#include?<linux/module.h>??#include?<linux/init.h>??#include?<linux/fs.h>??#include?<asm/uaccess.h>??MODULE_LICENSE("GPL");??#define?MAJOR_NUM?2918?//主設(shè)備號???static?ssize_t?device_read(struct?file?*,?char?*,?size_t,?loff_t*);??static?ssize_t?device_write(struct?file?*,?const?char?*,?size_t,?loff_t*);????struct?file_operations?device_fops?=??{?.read=device_read,?.write=device_write,?};??static?int?device_var?=?0;???static?int?__init?device_init(void)?{?int?ret;??ret?=?register_chrdev(MAJOR_NUM,?"device",?&device_fops);?if?(ret)?{?printk("device?register?failure");?}?else?{?printk("device?register?success");?}?return?ret;?}??static?void?__exit?device_exit(void)?{?int?ret?=?0;??unregister_chrdev(MAJOR_NUM,?"device");?if?(ret)?{?printk("device?unregister?failure");?}?else?{?printk("device?unregister?success");?}?}??static?ssize_t?device_read(struct?file?*filp,?char?*buf,?size_t?len,?loff_t?*off)?{??if?(copy_to_user(buf,?&device_var,?sizeof(int)))?{?return?-?EFAULT;?}?return?sizeof(int);?}?static?ssize_t?device_write(struct?file?*filp,?const?char?*buf,?size_t?len,?loff_t?*off)?{??if?(copy_from_user(&device_var,?buf,?sizeof(int)))?{?return?-?EFAULT;?}?return?sizeof(int);?}?module_init(device_init);?module_exit(device_exit);? 編譯為模塊:
命令為:make -C /lib/modules/3.0.0-7-generic/build M(等號)/home/shi/c_dev/modules
Makefile為
?
#?From《Linux?Device?Drivers》3rd?Edition?#?Makefile?ifneq?($(KERNELRELEASE),)?#?call?from?kernel?build?system??obj-m???:=?device.o??else??KERNELDIR??=?/lib/modules/$(shell?uname?-r)/build?PWD???????:=?$(shell?pwd)??default:?????$(MAKE)?-C?$(KERNELDIR)?M=$(PWD)?modules??endif?? 完成之后,講模塊加入到內(nèi)核中去
sudo insmod ./device.ko
查看所有模塊
lsmod
刪除模塊
sudo rmmod ./device.ko
測試程序
?
#include?<sys/types.h>?#include?<sys/stat.h>?#include?<stdio.h>?#include?<fcntl.h>?main()?{?int?fd,num;??fd?=?open("/dev/device",?O_RDWR,?S_IRUSR?|?S_IWUSR);?if?(fd?!=?0)?{??read(fd,?&num,?sizeof(int));?printf("The?device?is?%d\n",?num);??printf("Please?input?the?num?written?to?device\n");?scanf("%d",?&num);?write(fd,?&num,?sizeof(int));??read(fd,?&num,?sizeof(int));?printf("The?device?is?%d\n",?num);??close(fd);?}?else?{?printf("Device?open?failure\n");?}?}?? 運行結(jié)果
shi@smkoo:~/c_dev$ ./test
The device is 134514219
Please input the num written to device
1
The device is 1
?
轉(zhuǎn)載于:https://blog.51cto.com/1793109/709506
總結(jié)
以上是生活随笔為你收集整理的LInux 字符设备驱动程序的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。