如何编写一个Linux内核模块,这次手把手教你【建议小白收藏】

Linux:Hello World 模块 前言Linux 系统为应用程序提供了功能强大且容易扩展的 API,但在某些情况下,这还远远不够。与硬件交互或进行需要访问系统中特权信息的操作时,就需要一个内核模块。下面从 Hello World 模块来说明模块的建立与运行。 环境搭建 开始编写Linux内核模块之前,我们首先要准备一些工具。最重要的是,你需要有一台Linux机器,尽管可以使用任何Linux发行版,但本文中,我使用的是Ubuntu 16.04 LTS,如果你使用的其他发行版,可能需要稍微调整安装命令。 建立 1、创建目录 mkdir -p 阅读详情

一,前言

Linux 系统为应用程序提供了功能强大且容易扩展的 API,但在某些情况下,这还远远不够。与硬件交互或进行需要访问系统中特权信息的操作时,就需要一个内核模块。

Linux 内核模块是一段编译后的二进制代码,直接插入 Linux 内核中,在 Ring 0 (x86–64处理器中执行最低和受保护程度最低的执行环)上运行。这里的代码完全不受检查,但是运行速度很快,可以访问系统中的所有内容。

Intel X86架构使用了4个级别来标明不同的特权级。 Ring 0 实际就是内核态,拥有最高权限。而一般应用程序处于 Ring 3状态--用户态。在Linux中,还存在 Ring 1 和 Ring 2 两个级别,一般归属驱动程序的级别。在Windows平台没有 Ring 1 和 Ring 2 两个级别,只用 Ring 0 内核态和 Ring 3 用户态。在权限约束上,高特权等级状态可以阅读低特权等级状态的数据,例如进程上下文、代码、数据等等,但反之则不可。 Ring 0 最高可以读取 Ring 0-3 所有的内容, Ring 1 可以读 Ring 1-3 的, Ring 2 以此类推, Ring 3 只能读自己的数据。

 

二,为什么要开发内核模块

 编写Linux内核模块并不是因为内核太庞大而不敢修改。直接修改内核源码会导致很多问题,例如:通过更改内核,你将面临数据丢失和系统损坏的风险。内核代码没有常规Linux应用程序所拥有的安全防护机制,如果内核发生故障,将锁死整个系统。

更糟糕的是,当你修改内核并导致错误后,可能不会立即表现出来。如果模块发生错误,在其加载时就锁定系统是最好的选择,如果不锁定,当你向模块中添加更多代码时,你将会面临失控循环和内存泄漏的风险,如果不小心,它们会随着计算机继续运行而持续增长,最终,关键的存储器结构甚至缓冲区都可能被覆盖。

编写内核模块时,基本是可以丢弃传统的应用程序开发范例。除了加载和卸载模块之外,你还需要编写响应系统事件的代码(而不是按顺序模式执行的代码)。通过内核开发,你正在编写API,而不是应用程序。

你也无权访问标准库,虽然内核提供了一些函数,例如 printk (可替代printf)和 kmalloc (以与malloc相似的方式运行),但你在很大程度上只能使用自己的设备。此外,在卸载模块时,你需要将自己清理干净,系统不会在你的模块被卸载后进行垃圾回收。

三,开发的工具准备

开始编写Linux内核模块之前,我们首先要准备一些工具。最重要的是,你需要有一台Linux机器,尽管可以使用任何Linux发行版,但本文中,我使用的是Ubuntu 16.04 LTS,如果你使用的其他发行版,可能需要稍微调整安装命令。

其次,你需要一台物理机或虚拟机,我不建议你直接使用物理机编写内核模块,因为当你出错时,主机的数据可能会丢失。在编写和调试内核模块的过程中,你至少会锁定机器几次,内核崩溃时,最新的代码更改可能仍在写缓冲区中,因此,你的源文件可能会损坏,在虚拟机中进行测试可以避免这种风险。

最后,你至少需要了解一些C。对于内核来说,C++在运行时太大了,因此编写纯C代码是必不可少的。另外,对于其与硬件的交互,了解一些组件可能会有所

操作系统实验-添加一个内核模块 操作系统课程实验-添加一个内核模块 阅读详情

相关推荐

[Linux驱动开发一]最简单的内核模块

[Linux驱动开发一]最简单的内核模块

weixin_42857944的博客 3409

linux编写一个简单的内核模块

编写一个简单的内核模块 (一)实验目的 Linux 操作系统的内核是单一体系结构(monolithic kernel)的,也就是说,整个内核是一个单独的非常大的程序。这样,系统的速度和性能都很好,但是可扩展性和维护性就相对比较差。为了弥补单一体系结构的这种缺陷,Linux操作系统使用了一种全新的机制-模块机制,用户可以根据需要,在不需要对内核重新编译的情况下,模块能动态地载入内核或从内核移出。 本...

qq_41032508的博客 5527

编写一个简单的内核模块

#include #include #include static int __init lkp_init(void) { printk(KERN_EMERG"Hello,Kernel!\n"); printk(KERN_ALERT"Hello,Kernel!\n"); printk(KERN_CRIT"Hello,Kernel!\n"); printk(KE

FallingU的博客 1万+

Pixhawk RPi CM4 Baseboard 树莓派CM4安装Ubuntu20.04 server 配置ros mavros mavsdk

cm4配置ros mavros连接pixhawk4 Pixhawk RPi CM4 Baseboard

baidu_41704597的博客 2127

从零开始学习信号完整性(SIPI)--2

上一节我们已经谈过,信号完整性研究的是如何使驱动器输出的信号传输到接收器件并被正确的接收。 信号完整性的三要素包含了:信号、驱动接收芯片、传输通道。 这其中信号是主体,我们要做的主要工作就是设计好信号的传输路径为信号的正确传输扫清障碍。要做信号完整性分析与设计首先要了解信号的特性,以及信号质量的判别标准。 对一个信号进行描述通常需要如下几个指标: 信号特性的描述 摆幅:信号从低电平到高电平之间的电压差,对于单端信号通常由信号的供电电压决......

qq_29476769的博客 2万+

LWIP协议栈在STM32H7上的内存优化实战:如何用32KB RAM实现稳定千兆以太网通信

本文深入探讨了在STM32H7微控制器上,如何通过内存优化策略,在仅32KB的D2 SRAM中稳定运行LWIP协议栈以实现千兆以太网通信。文章详细分析了STM32H7的内存架构、LWIP的内存消耗瓶颈,并提供了从描述符表与PBUF池精确分配、链接脚本修改到MPU区域划分的一整套实战优化方案,旨在解决大数据量传输卡死等常见配置问题。

gg901的博客 603

GeoServer下载与安装(详细图文教程)

GeoServer官方版可以方便的发布地图数据,允许用户对特征数据进行更新、删除、插入操作,通过 GeoServer 可以比较容易的在用户之间迅速共享空间地理信息。

大剑师兰特的GIS世界 3275

2026年3月GESP真题及题解(C++七级):物流网络

2026年3月GESP真题及题解(C++七级):物流网络

王老师青少年编程 1124

《python算法与数据结构2000讲》算法与数据结构总结

《python算法与数据结构2000讲》算法与数据结构总结

IT 甄选推荐 1103

Nature Communications|马兰戈尼效应构建空心金字塔微阵列制备高灵敏度柔性电容式压力传感器(健康监测/柔性压力传感/柔性电子/人机交互)

三维(3D)微结构因其在柔软性、轻质化、对3D表面的贴合性和可压缩性方面的显著优势,已经在生物医学监测、人机接口、机器人触觉和微型飞行器等领域引起了广泛关注。柔性电容式压力传感器(CPSs),由两片平行板组成,中间夹着一层软介电薄膜,具有设备构造简单、高灵敏度和快速响应速度等众多吸引人的优点。结构化介电层的三维机械设计在决定传感器性能方面起着至关重要的作用,如灵敏度(这是压力传感器的关键特性,因为它决定了感知微小压力和获取更多细节的能力,如轻柔触摸和脉搏检测)。

感知科学前沿 526

【OpenClaw企业级智能体实战】第10篇:医疗行业OpenClaw实战:病历自动书写、医保智能审核与患者随访管理(附HIPAA合规配置+完整代码)

医疗行业正面临“效率提升需求”与“合规监管红线”的双重矛盾:病历书写占据医生30%-50%工作时间,医保审核效率低下,患者随访工作量巨大,但医疗数据“不出域”“责任不转移”的要求又限制了AI落地。本文基于华为云、腾讯云安全规范及中关村科金、复旦大学附属中山医院等真实实践,拆解OpenClaw在医疗场景的五大核心应用(病历自动书写、医保智能审核、患者随访管理、科研文献综述、医学影像预处理),提供私有化部署架构、HIPAA合规配置模板、完整实操流程及可直接运行的代码。

专注于人工智能、软件开发、工控自动化、工厂数字化及智能化等领域,希望和大家共同进步! 439

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

上一篇: 作为现在程序员必备的Linux内核(让你十分钟快速了解)
下一篇: 深度还原Linux内核工作原理【建议小白收藏】
書生途66
博客等级 码龄5年 1粉丝 5原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值