一个简单的杂项字符设备模块注册与验证(全套)

驱动模块端:

#include <linux/module.h>
#include <linux/kernel.h>
#include <asm/uaccess.h>
#include <linux/fs.h>
#include <linux/miscdevice.h>
#include <asm/io.h>


#define  GPM4CON  0x110002e0
#define  GPM4DAT  0x110002e4

static unsigned  long*  ledcon = NULL;
static unsigned  long*  leddat = NULL;

//文件操作函数是在驱动中定义,在应用层调用!    write(fd,  buf,  strlen(buf));
//实现文件操作函数的功能
static  ssize_t led_misc_write(struct file* filp, const char __user* buff, size_t count, loff_t* off)
{
    int ret = 0;
    char buf[32] = {0};
    
    ret = copy_from_user(buf, buff, count);
    if(strncmp(buf, "led on", strlen("led on")) == 0)
    {
        printk("---led on---\n");
        *leddat  &=  0xf0;
    }
    else if(strncmp(buf, "led off", strlen("led off")) == 0)
    {
        printk("---led off---\n");
        *leddat |= 0x0f;
    }
    else
    {
        printk("***led error***\n");
    }

    return count;
}


//声明对上提供哪些文件操作函数
static  struct file_operations  g_tfops = {
        .owner    =    THIS_MODULE,
        .write    =    led_misc_write,
};

//杂项字符设备定义、初始化
static  struct miscdevice  g_tmisc = {
    .minor    =    MISC_DYNAMIC_MINOR,
    .name    =    "led_misc",
    .fops    =    &g_tfops,
};

static  int  __init  xyd_misc_init(void)
{
    ledcon = ioremap(GPM4CON, 4);
    leddat = ioremap(GPM4DAT, 4);

    *ledcon  &= 0xffff0000;
    *ledcon  |= 0x00001111;
    *leddat  |= 0x0f;

    //杂项字符设备注册
    misc_register(&g_tmisc);

    return 0;
}

static  void  __exit  xyd_misc_exit(void)
{
    misc_deregister(&g_tmisc);
    iounmap(ledcon);
    iounmap(leddat);
}

module_init(xyd_misc_init);
module_exit(xyd_misc_exit);

MODULE_LICENSE("GPL");

 

 

makefile


FILE = misc_led

obj-m = $(FILE).o

KDIR = /work/linux-3.5/

all:
    make -C  $(KDIR)  M=$(PWD) modules

cp:
    cp  /mnt/hgfs/lesson/test/$(FILE).c     ./

chmod:
    chmod 666 $(FILE).c

clean:
    rm .*.cmd  *.mod*  *.o  *.order  *.symvers  .tmp* -rf

nfs:
    cp ./*.ko  /work/root_nfs/demo
 

 

make。sh

#!/bin/bash

make cp
make chmod
make 
make clean
make nfs
 

 

app

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

int main(int argc, char* argv[])
{
    int fd = 0;
    fd = open(argv[1], O_RDWR);
    if(fd < 0)
    {
        printf("open %s failed!\n", argv[1]);
        return -1;
    }

    char buf[32] = {0};
    while(1)
    {
        memset(buf, 0, sizeof(buf));
        fgets(buf, sizeof(buf), stdin);
        write(fd, buf, strlen(buf));  
    }
    
    close(fd);
    return 0;
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值