草庐IT

ubuntu编译字符设备

梦起白沙 2023-09-13 原文

前言

创建一个简单的字符设备驱动程序。

​ 本文命令的运行基本上都需要root权限,使用root账号,或者在命令前面加上sudo。

​ 如果你使用ssh远程连接的服务器进行代码编写。那么不要在root用户下创建文件或者文件夹。这会导致你ssh连接vscode编写代码的权限问题。可以在普通用户创建好所有的文件,然后编写。

代码

驱动程序

hello_driver.c

#include <linux/types.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/cdev.h>
 
 
dev_t hello_devid;
struct cdev hello_cdev;
int hello_major = 0;
int hello_minor;
 
 
uint8_t kernel_buffer[1024] = {0};
static struct class *hello_class;
 
 
 
static int hello_world_open(struct inode * inode, struct file * file)
{
	printk("hello_world_open\r\n");
	return 0;
}
 
static int hello_world_release (struct inode * inode, struct file * file)
{
	printk("hello_world_release\r\n");
	return 0;
}
 
static ssize_t hello_world_read (struct file * file, char __user * buffer, size_t size, loff_t * ppos)
{
	printk("hello_world_read size:%ld\r\n",size);
	copy_to_user(buffer,kernel_buffer,size);
	return size;
}
 
static ssize_t hello_world_write(struct file * file, const char __user * buffer, size_t size, loff_t *ppos)
{
	printk("hello_world_write size:%ld\r\n",size);
	copy_from_user(kernel_buffer,buffer,size);
	return size;
}
 
 
static const struct file_operations hello_world_fops = {
	.owner		= THIS_MODULE,
	.open		= hello_world_open,
	.release = hello_world_release,
	.read		= hello_world_read,
	.write	= hello_world_write,
};
 
 
static int __init hello_driver_init(void)
{
	int ret;
	printk("hello_driver_init\r\n");
 
	alloc_chrdev_region(&hello_devid, 0, 1, "hello");
	hello_major = MAJOR(hello_devid);
	hello_minor = MINOR(hello_devid);
	printk("hello driver major=%d,minor=%d\r\n",hello_major, hello_minor);	
 
	hello_cdev.owner = THIS_MODULE;
	cdev_init(&hello_cdev, &hello_world_fops);
	cdev_add(&hello_cdev, hello_devid, 1);
	
	hello_class = class_create(THIS_MODULE,"hello_class");
 
	device_create(hello_class,NULL,hello_devid,NULL,"hello"); /* /dev/hello */
 
	return 0;
}
 
static void __exit hello_driver_cleanup(void)
{
	printk("hello_driver_cleanup\r\n");
	cdev_del(&hello_cdev);
	unregister_chrdev_region(hello_devid, 1);
	
	device_destroy(hello_class,hello_devid);
	class_destroy(hello_class);
	
}
 
 
module_init(hello_driver_init);
module_exit(hello_driver_cleanup);
MODULE_LICENSE("GPL");

Makefile文件

KERNELDIR := /lib/modules/$(shell uname -r)/build
CURRENT_PATH := $(shell pwd)
obj-m := hello_driver.o

KBUILD_CFLAGS   += -Wno-unused-result -Wno-unused-variable
build: kernel_modules
 
kernel_modules:
	$(MAKE) ${CFLAGS} -C $(KERNELDIR) M=$(CURRENT_PATH) modules
	$(CROSS_COMPILE)gcc -o test_app test_app.c
clean:
	$(MAKE) -C $(KERNELDIR) M=$(CURRENT_PATH) clean
	rm -rf test_app

测试程序

test_app.c

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

uint8_t buffer[512] = {0};
 
int main(int argc, char *argv[])
{
	int fd;
	int ret;
	
	fd  = open(argv[1], O_RDWR);
    if(!fd)
    {
        printf("everthing is error\n");
    }
 
	if(!strcmp("read",argv[2]))
	{
		printf("read data from kernel\r\n");
		ret = read(fd,buffer,sizeof(buffer));
		printf("ret len:%d data:%s\r\n",ret,buffer);
	}
 
	if(!strcmp("write",argv[2]))
	{
		printf("write data to kernel %s len:%ld\r\n",argv[3],strlen(argv[3]));
		ret = write(fd,argv[3],strlen(argv[3]));
		printf("ret len:%d\r\n",ret);
	}
 
	
	close(fd);
 
	
}

编译

执行make命令编译

root@ubuntu:/home/dong/workspace/drivercode# make
make  -C /lib/modules/5.19.0-38-generic/build M=/home/dong/workspace/drivercode modules
make[1]: Entering directory '/usr/src/linux-headers-5.19.0-38-generic'
warning: the compiler differs from the one used to build the kernel
  The kernel was built by: x86_64-linux-gnu-gcc (Ubuntu 11.3.0-1ubuntu1~22.04) 11.3.0
  You are using:           gcc (Ubuntu 11.3.0-1ubuntu1~22.04) 11.3.0
  CC [M]  /home/dong/workspace/drivercode/hello_driver.o
  MODPOST /home/dong/workspace/drivercode/Module.symvers
  CC [M]  /home/dong/workspace/drivercode/hello_driver.mod.o
  LD [M]  /home/dong/workspace/drivercode/hello_driver.ko
  BTF [M] /home/dong/workspace/drivercode/hello_driver.ko
Skipping BTF generation for /home/dong/workspace/drivercode/hello_driver.ko due to unavailability of vmlinux
make[1]: Leaving directory '/usr/src/linux-headers-5.19.0-38-generic'
gcc -o test_app test_app.c

会生成hello_driver.ko文件和test_app

加载模块

insmod hello_driver.ko

卸载模块

rmmod hello_driver

查看模块

lsmod |grep hello_driver

运行测试

创建设备文件

这个文件不是随便创造的,会分配设备号,如果不使用分配的设备号创建会出现读写错误。

​ 每一次加载或者卸载模块都会有dmesg信息。

​ 使用dmesg -c清除信息。加载模块,使用dmesg查看模块信息。

root@ubuntu:/home/dong/workspace/drivercode# dmesg
[164284.337396] hello_driver_init
[164284.337399] hello driver major=238,minor=0

我的设备主设备号就是238,从设备号是0

创建设备文件命令

mknod /dev/hello c 238 0

测试

读 : ./test_app /dev/hello read

写: ./test_app /dev/hello write 需要写入的内容

有关ubuntu编译字符设备的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. Ruby 解析字符串 - 2

    我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?

  3. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  4. ruby-on-rails - unicode 字符串的长度 - 2

    在我的Rails(2.3,Ruby1.8.7)应用程序中,我需要将字符串截断到一定长度。该字符串是unicode,在控制台中运行测试时,例如'א'.length,我意识到返回了双倍长度。我想要一个与编码无关的长度,以便对unicode字符串或latin1编码字符串进行相同的截断。我已经了解了Ruby的大部分unicode资料,但仍然有些一头雾水。应该如何解决这个问题? 最佳答案 Rails有一个返回多字节字符的mb_chars方法。试试unicode_string.mb_chars.slice(0,50)

  5. ruby - 将差异补丁应用于字符串/文件 - 2

    对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl

  6. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  7. ruby - 如何以所有可能的方式将字符串拆分为长度最多为 3 的连续子字符串? - 2

    我试图获取一个长度在1到10之间的字符串,并输出将字符串分解为大小为1、2或3的连续子字符串的所有可能方式。例如:输入:123456将整数分割成单个字符,然后继续查找组合。该代码将返回以下所有数组。[1,2,3,4,5,6][12,3,4,5,6][1,23,4,5,6][1,2,34,5,6][1,2,3,45,6][1,2,3,4,56][12,34,5,6][12,3,45,6][12,3,4,56][1,23,45,6][1,2,34,56][1,23,4,56][12,34,56][123,4,5,6][1,234,5,6][1,2,345,6][1,2,3,456][123

  8. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  9. ruby - 如何使用文字标量样式在 YAML 中转储字符串? - 2

    我有一大串格式化数据(例如JSON),我想使用Psychinruby​​同时保留格式转储到YAML。基本上,我希望JSON使用literalstyle出现在YAML中:---json:|{"page":1,"results":["item","another"],"total_pages":0}但是,当我使用YAML.dump时,它不使用文字样式。我得到这样的东西:---json:!"{\n\"page\":1,\n\"results\":[\n\"item\",\"another\"\n],\n\"total_pages\":0\n}\n"我如何告诉Psych以想要的样式转储标量?解

  10. ruby 正则表达式 - 如何替换字符串中匹配项的第 n 个实例 - 2

    在我的应用程序中,我需要能够找到所有数字子字符串,然后扫描每个子字符串,找到第一个匹配范围(例如5到15之间)的子字符串,并将该实例替换为另一个字符串“X”。我的测试字符串s="1foo100bar10gee1"我的初始模式是1个或多个数字的任何字符串,例如,re=Regexp.new(/\d+/)matches=s.scan(re)给出["1","100","10","1"]如果我想用“X”替换第N个匹配项,并且只替换第N个匹配项,我该怎么做?例如,如果我想替换第三个匹配项“10”(匹配项[2]),我不能只说s[matches[2]]="X"因为它做了两次替换“1fooX0barXg

随机推荐