电子产品世界 » 论坛首页 » 企业专区 » STM32 » 一个简单的linux设备驱动和应用测试代码

共1条 1/1 1 跳转至

一个简单的linux设备驱动和应用测试代码

高工
2018-12-11 08:12:57    评分

1 驱动源文件


2 Makefile


3 应用测试




#include <linux/module.h>

#include <linux/init.h>

#include <linux/types.h>

#include <linux/fs.h>

#include <linux/mm.h>

#include <linux/cdev.h>

#include <linux/errno.h>

#include <linux/sched.h>

#include <linux/io.h>

#include <asm/system.h>

#include <asm/uaccess.h>


#define sddev_MAJOR 200

static unsigned char dev_inc = 0;

static char devbuffer[256];

int dev_open(struct inode *inode,struct file *filp)

{

    if(dev_inc > 0)

        return -ERESTARTSYS;

    dev_inc++;

    return 0;

    

}

int dev_release(struct inode *inode,struct file *filp)

{

    dev_inc--;

    return 0;

    

}

ssize_t dev_read(struct file *filp,char __user *buf,size_t count,loff_t *f_pos)

{

    if(copy_to_user(buf,devbuffer,count))

    {

        count = -EFAULT;

        

    }

    return count;

}

ssize_t dev_write(struct file *file,const char __user *buf,size_t count,loff_t *f_pos)

{

    if(copy_from_user(devbuffer + *f_pos, buf, count))

        count = -EFAULT;

    return count;

    

}

void dev_exit_module(void)

{

    unregister_chrdev(sddev_MAJOR,"sddev");

    printk("dev_exit_module!\n");

}



static const struct file_operations dev_fops={

    .owner  = THIS_MODULE,

    .open   = dev_open,

    .write  = dev_write,

    .read   = dev_read,

    .release = dev_release, 


};

int dev_init_module(void)

{

    int ret;

    ret = register_chrdev(sddev_MAJOR,"sddev",&dev_fops);

    if(ret < 0)

    {

        printk("Unable to register sddev device driver!\n");

        return ret;

    }

    return 0;

}

module_init(dev_init_module);

module_exit(dev_exit_module);


MODULE_LICENSE("Dual BSD/GPL");




2


ifneq ($(KERNELRELEASE),)

    obj-m := sddev.o

else

    KERNELDIR ?= /lib/modules/$(shell uname -r)/build

    PWD := $(shell pwd)

    

all:

    make -C $(KERNELDIR) M=$(PWD) modules

    

clean:

    rm -f *.ko *.o *.mod.c *.symvers

    

endif



3


#include <stdio.h>

#include <fcntl.h>

int main(void)

{

    int fd;

    int i;

    char data[256];

    int retval;

    fd = open("/dev/sddev",O_RDWR);

    if(fd == -1)

    {

        printf("error open\n");

        exit(-1);

    }

    printf("open /dev/sddev OK!\n");

    

    retval = write(fd, "safwwwwwweeeeeee",16);

    if(retval == -1)

    {

        printf("write error\n");

        exit(-1);

    }

    retval = read(fd, data,16);

    if(retval == -1)

    {

        printf("read error!\n");

        exit(-1);

    }

    

    data[retval]=0;

    printf("read OK! %s\n",data);

    

    close(fd);

    return 0;

    

}


--------------------- 





共1条 1/1 1 跳转至

回复

匿名不能发帖!请先 [ 登陆 注册 ]