[drive program]helloworld

Referce: https://www.cnblogs.com/amanlikethis/p/4914510.html

1.Compile drive program

Add hello.c hellotest.c Makefile in a total directory. Then input "make"  to compile.

2.Compile appication program

gcc hellotest.c -o hellotest

3. Install mudule.

sudo insmod hellomodule.ko

Then input "dmesg", will see the message of mudule prinf, as below:

See mudle if install succedful: use command cat /proc/modules

or just use command

lsmod

4.Creat Node

扫描二维码关注公众号,回复: 4722598 查看本文章
sudo mknod /dev/hellodev c 231 0

If success, as bellow:

5.Run the application.

6.Remove mudule

sudo rmmod hellomodule

Appendix: Source file

hello.c

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/delay.h>

#define    HELLO_MAJOR     231
#define    DEVICE_NAME     "HelloModule"

static int hello_open(struct inode *inode, struct file *file){
    printk(KERN_EMERG "hello open.\n");
    return 0;
}
	
static ssize_t hello_write(struct file *pFile, const char __user * buf, size_t count, loff_t *ppos){
    printk(KERN_EMERG "hello write.\n");
    return 0;
}

static struct file_operations hello_flops = {
    .owner  =   THIS_MODULE,
    .open   =   hello_open,     
    .write  =   hello_write,
};

static int __init hello_init(void){
    int ret;
    
    ret = register_chrdev(HELLO_MAJOR,DEVICE_NAME, &hello_flops);
    if (ret < 0) {
      printk(KERN_EMERG DEVICE_NAME " can't register major number.\n");
      return ret;
    }
    printk(KERN_EMERG DEVICE_NAME " initialized.\n");
    return 0;
}

static void __exit hello_exit(void){
    unregister_chrdev(HELLO_MAJOR, DEVICE_NAME);
    printk(KERN_EMERG DEVICE_NAME " removed.\n");
}

module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");

Makefile:

ifneq ($(KERNELRELEASE),)
MODULE_NAME = hellomodule
$(MODULE_NAME)-objs := hello.o
obj-m := $(MODULE_NAME).o
else
KERNEL_DIR = /lib/modules/`uname -r`/build
MODULEDIR := $(shell pwd)

.PHONY: modules
default: modules

modules:
	make -C $(KERNEL_DIR) M=$(MODULEDIR) modules

clean distclean:
	rm -f *.o *.mod.c .*.*.cmd *.ko
	rm -rf .tmp_versions
endif

Application program:

hellotest.c

#include <fcntl.h>
#include <stdio.h>

int main(void)
{
    int fd;
    int val = 1;
    fd = open("/dev/hellodev", O_RDWR);
    if(fd < 0){
        printf("can't open!\n");
    }
    write(fd, &val, 4);
    return 0;
}

(end)

猜你喜欢

转载自blog.csdn.net/zhuohui307317684/article/details/85163956
今日推荐