mydevice.c

来自「Linux 下的字符驱动程序」· C语言 代码 · 共 56 行

C
56
字号
#ifndef __KERNEL__
#define __KENEL__
#endif
#ifndef MODULE
#define MODULE
#endif

#include <linux/module.h>
#include <linux/types.h>
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/errno.h>
#include <asm/segment.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <asm/uaccess.h>
#include <asm/io.h>
#include <linux/ioport.h>
int my_major=0; /*设备号*/
static int Device_Open=0;
static char Message[128];
char *Message_Ptr;
/*--------------------my_open----------------------*/
/*--------------------------------------------------*/
int my_open(struct inode *inode, struct file *file)
{   
    static int counter=0;
    printk("<1>device_open(%p,%p) is called\n",inode,file);
    if(Device_Open)
        return  -EBUSY;/*同时只能供一台设备打开*/
    Device_Open++;      /*引用计数加1*/
    sprintf(Message,"this is from my_device,it has been called %d times\n",counter++);
    return 0;
}

/*--------------------my_release-------------------*/
/*--------------------------------------------------*/
int my_release(struct inode *inode, struct file *file)
{
    printk("<1>device_release(%p,%p) is called\n",inode,file);
    Device_Open--;      /*引用计数减1*/
    printk("<1>the device has been released\n");
    return 0;
}

/*--------------------my_read----------------------*/
/*--------------------------------------------------*/
ssize_t my_read(struct file *file,char *buf,int size,loff_t off)
{
    ssize_t bytes_read=0;
    printk("<1>my_read is called,User buffer is %p,size is %d\n",buf,size);

    Message_Ptr=Message;
    while(size&&*Message_Ptr)
    {
        if(put_user(*(Message_Ptr++),buf++))  /*鍐欐暟鎹

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?