linux 嵌入式驱动程序实例

#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/malloc.h>
#include <asm/uaccess.h>
#include <linux/errno.h>

unsigned int fs_major = 0;
static char *data;

statoc struct file_operations chr_fopt = {
   read:  test_read,
   write: test_write,
   open:  test_open,
   release: test_release,
 };
 
 
static ssize_t test_read(struct file* file,char *buf,size_t count,loff_t *f_pos);
static ssize_t test_write(struct file* file,const char *buffer,size_t count,loff_t *f_pos);
static int test_open(struct inode* inode,struct file* file);
static int test_release(struct inode* inode,struct file* file);
int init_module(vod);
void cleanup_module(void);


static ssize_t test_read(struct file* file,char *buf,size_t count,loff_t *f_pos)
{
 int len;
 if( count < 0 )
   return -EINVAL;
 len = strlen(data);
 if( len < count )
   count = len;
 copy_to_user(buf,data,count+1);
 return count;
}


static ssize_t test_write(struct file* file,const char *buffer,size_t count,loff_t *f_pos)
{
  if( count < 0 )
    return -EINVAL;
  kfree(data);
  data = NULL;
  data = (char *)kmalloc(sizeof(char) * (count + 1 ),GFP_KERNEL);
  if(!data)
    return -ENOMEM;
  copy_from_user(data,buffer,count+1);
  return count;
}

static int test_open(struct inode* inode,struct file* file)
{
  MOD_INC_USE_COUNT;
  printf("This is open/n");
  return 0;
}

static int test_release(struct inode* inode,struct file* file)
{
  MOD_DEC_USE_COUNT;
  printf("This is released/n");
  return 0;
}

int init_module(vod)
{
  int res;
  res = register_chrdev(0,"fs",&chr_fops);
  if( res < 0 )
  {
   printfk("can't get major name!/n");
   return res;
  }
  if( fs_major == 0 )
   fs_major = res;
  return 0;
}

void cleanup_module(void)
{
 unregister_chrdev(fs_major,"fs");
}

//arm-linux-gcc -DMODULE -D__KERNEL__ -c kernel.C

//加载模块
//insmod ./kernel.o

//查看设备号
//vi /proc/device

//映射为设备文件
//mknod /dev/fs c 254 0
// dev/fs就是相应的设备文件,c代表字符文件,254代表主设备号,0为次设备号

你可能感兴趣的:(linux 嵌入式驱动程序实例)