文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>10.04.22

10.04.22

时间:2010-04-23  来源:donotgiveup

·环境 fc9+VMware7  自己写了个最简单的字符驱动。没有考虑代码的美观,只是为了测试。
·字符设备驱动代码如下

// file: chrdev.c

#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/fs.h> // struct inode
#include <linux/cdev.h> // struct cdev
#include <asm/uaccess.h> // copy_from_user
//#include <linux/>


#define    DEV_MAJOR_NUM    113
#define    DEV_MINOR_NUM    8
#define    DEV_NAME        "GOD"

MODULE_LICENSE("Dual BSD/GPL");

static int z_ioctl(struct inode *, struct file *, unsigned int, unsigned long);

struct z_dev
{
    struct cdev cdev;
    char *p_mem; // 没有用到
};

struct z_dev *s_p_dev = NULL;

struct file_operations s_fops =
{
    .ioctl = z_ioctl, // ","
};

static int z_ioctl(struct inode * p_node, struct file *flp, unsigned int cmd, unsigned long param)
{
    int buff[5] = {1,2,3,4,5};
    copy_to_user((void*)param, buff, 5*sizeof(int));
    return 0;
}

static int __init init(void)
{
    struct z_dev *p_dev = NULL;

    // dev_t register

    dev_t dev_no = MKDEV(DEV_MAJOR_NUM, 0); // 次设备号不是0就失败?
    if(register_chrdev_region(dev_no, 1, DEV_NAME)!=0)
    {

        printk("register_chrdev_region err\n");
    }
    
    // cdev register

    p_dev = (struct z_dev *)kmalloc(sizeof(struct z_dev), 0);
    if (p_dev==NULL)
    {

        printk("kmalloc err\n");
    }

    cdev_init(&p_dev->cdev, &s_fops);
    p_dev->cdev.owner    = THIS_MODULE;
    p_dev->cdev.ops        = &s_fops;

    if (cdev_add(&p_dev->cdev, dev_no, 1)!=0)
    {

        printk("cdev_add err\n");
    }

    s_p_dev = p_dev;
    return 0;
}

static void __exit exit(void)
{
    dev_t dev_no = MKDEV(DEV_MAJOR_NUM, 0);
    unregister_chrdev_region(dev_no, 1);
    cdev_del(&s_p_dev->cdev);
    if (s_p_dev!=NULL) kfree(s_p_dev);
    return;
}

module_init(init);
module_exit(exit);

·Makefile

obj-m := chrdev.o
PWD    := $(shell pwd)
KDIR    := /lib/modules/$(shell uname -r)/build
default:
    $(MAKE) -C $(KDIR) M=$(PWD) modules

·测试文件 test.c 测试前需要mknod /dev/god c 113 0

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

int main(int argc,char** argv)
{
    int fd = -1;
    int i;
    if ((fd=open("/dev/god", O_RDWR))==-1)
    {
        printf("open err\n");
        return 1;
    }
    int buff[5];
    ioctl(fd, 0, buff);
    for(i=0;i<5;i++)
    {
        printf("%4d",buff[i]);
    }
    printf("\n");
    if (close(fd)!=0)
    {
        printf("close err\n");
        return 1;
    }
    return 0;
}

·以上文件放在同一个目录 1.sh

#!/bin/sh
clear;
make;
rmmod chrdev.ko;
insmod chrdev.ko;
tail /var/log/messages;
cat /proc/devices

2.sh

#!/bin/sh
clear
rmmod chrdev
cat /proc/devices

3.sh

#!/bin/sh
gcc test.c -o t
./t

修改属性
chmod +x *.sh
·编译运行 ./1.sh ./3.sh 输出 1 2 3 4 5表示成功了。 ./2.sh
相关阅读 更多 +
排行榜 更多 +
哥布林弹球b服手游下载

哥布林弹球b服手游下载

休闲益智 下载
小马样式盒游戏下载

小马样式盒游戏下载

休闲益智 下载
异变小镇中文版下载安装

异变小镇中文版下载安装

冒险解谜 下载