Linux系统启动时如何实现驱动程序的加载和应用程序的运行(自启动)【利用脚本/etc/init.d/rcS】

发布于:2025-02-11 ⋅ 阅读:(17) ⋅ 点赞:(0)

引言

很多时候,我们希望自己写的驱动程序能在Linux系统启动时自动加载,自己写的应用程序也能自动运行,本篇博文就介绍如何实现这两件事。

思路很简单,系统启动时会自动加载脚本/etc/init.d/rcS,那么我们在脚本/etc/init.d/rcS写入我们要加载的模块或运行的程序就行了。

驱动程序的自动加载

以博文 https://blog.csdn.net/wenhao_ir/article/details/144973219 中的LED驱动程序为例,说明如何在Linux的系统启动时自动完成动自己写的驱动程序的加载。

将驱动程序复制到开发板的目录

打开串口终端→打开开发板→挂载网络文件系统

mount -t nfs -o nolock,vers=3 192.168.5.11:/home/book/nfs_rootfs /mnt

在根目录下建立一个名为mydriver的目录:

cd /
mkdir mydriver

在这里插入图片描述
将网络文件系统目录中的驱动复制到目录mydriver中。
在这里插入图片描述

cp /mnt/archived/017_led_driver/led_driver.ko /mydriver/

复制完成后检查有没有:
在这里插入图片描述
可见有了。

修改系统启动时要运行的脚本文件/etc/init.d/rcS

利用vi编辑器编辑脚本文件/etc/init.d/ rcS:

vi /etc/init.d/rcS

加入下面的代码:

insmod /mydriver/led_driver.ko

在这里插入图片描述
如果后面要取消这行代码的效果,在前面加 # 注释掉它就行了。

重启开发板看是否自动加载驱动模块了

然后重启开发板看是否自动加载驱动模块了…

reboot

看下相关设备文件有没有了:

ls /dev/

有了,就是下面截图中的:imx6ull_led0
在这里插入图片描述

应用程序的自动加载

程序的代码和编译

用户空间的代码如下:

#include <stdio.h>
#include <unistd.h>

int main() {
    while (1) {
        printf("Hello world! My name is SuWenhao.\n");
        fflush(stdout); // 确保输出立即刷新到终端
        sleep(3); // 休眠3秒
    }
    return 0;
}

gcc编译命令如下:

arm-buildroot-linux-gnueabihf-gcc -o print_hello_periodically print_hello_periodically.c

在这里插入图片描述

可执行程序复制到开发板的目录

挂载网络文件系统:

mount -t nfs -o nolock,vers=3 192.168.5.11:/home/book/nfs_rootfs /mnt

开发板根目录下新建目录myprogram

cd /
mkdir myprogram

在这里插入图片描述
复制ELF可执行程序 print_hello_periodically 到目录 myprogram 中:

cp /mnt/print_hello_periodically/print_hello_periodically /myprogram/

检查文件是否复制成功:

ls /myprogram

在这里插入图片描述
下面这一步不一定要做,但最好做一下,即把程序文件添加可执行权限:

chmod +x /myprogram/print_hello_periodically

修改系统启动时要运行的脚本文件/etc/init.d/rcS

利用vi编辑器编辑脚本文件/etc/init.d/rcS:

vi /etc/init.d/rcS

加入下面的代码:

# 启动程序 print_hello_periodically 并让其在后台运行
/myprogram/print_hello_periodically &

在这里插入图片描述
保存~

重启开发板看是否自动运行了

reboot

在这里插入图片描述
可见是自动运行了。

如何取消它们的自动运行

很简单,把相应的语句注释掉就行了,如下图所示:

vi /etc/init.d/rcS

在这里插入图片描述


网站公告

今日签到

点亮在社区的每一天
去签到