日期:2014-05-16  浏览次数:20714 次

弱弱的问一个,简单字符设备驱动程序,打开文件错误问题。
刚开始接触字符驱动就被吓到了,按着教科书的内容,整理了个最简单的字符驱动,加载上以后open打开返回总是-1,实在找不到原因了,驱动文件我也创建了,内核我也加载过了。

驱动部分代码:

#include <linux/slab.h>
#include <linux/fcntl.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/fs.h>
#include <linux/sysctl.h>
#include <linux/init.h>
#include <linux/cdev.h>
#include <asm/io.h>
#include <asm/system.h>
#include <asm/uaccess.h>

#define SCHAR_MAJOR 256
#define SCHAR_MINOR 0

struct cdev cdev;

int schar_open(struct inode *inode, struct file *filp){
printk("-------------------open--------------------");
return 0;
}

int schar_release(struct inode *inode, struct file *filp){
printk("-------------------close-------------------");
return 0;
}

ssize_t schar_read(struct file *filp, char __user *buff, size_t count, loff_t *offp){
printk("----------------read----------------\n");
return 0;
}

ssize_t schar_write(struct file *filp, char *buff, size_t count, loff_t *offp){
printk("-----------------write--------------\n");
return 0;
}
static struct file_operations schar_fops = {
  .owner = THIS_MODULE,
  .read = schar_read,
  .write = schar_write,
  .open = schar_open,
  .release= schar_release,
};
 
static int inits_module(void)
{
int res;
dev_t dev = 0;

dev = MKDEV(SCHAR_MAJOR, SCHAR_MINOR);
res = register_chrdev_region(dev, SCHAR_NR_DEVS, "schar");


if (res) {
printk("can't register device with kernel\n");
return res;
}else {
printk("--------Register device number:%d---------\n",(int)dev);
}

cdev_init(&cdev,&schar_fops);
cdev.owner = THIS_MODULE;
cdev.ops = &schar_fops;
cdev_add(&cdev,SCHAR_MINOR,SCHAR_NR_DEVS);

printk("-----------module loaded--------------\n");
return 0;
}

void cleanups_module(void)
{
printk("------------------------------------\n");
dev_t dev = MKDEV(SCHAR_MAJOR, SCHAR_MINOR);
cdev_del(&cdev);
kfree(schar_init);
unregister_chrdev_region(dev,SCHAR_NR_DEVS);
printk("----------------unloaded---------------\n");
return;
}

module_init(inits_module);
module_exit(cleanups_module);

测试代码:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/types.h> 
#include <sys/stat.h>
int buf[2];

int main(void)
{
   
  int fd, num;

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

  if (fd != -1 )
  {
  printf("The program is schar driver\n");

  close(fd);
  }
  else
  {
  printf("Device open failure\n");
  }
}


------解决方案--------------------
你这种写法需要手动创建设备节点
用mknod命令创建 /dev/schar
但是你好像没有创建,当然失败了
------解决方案--------------------
同意一楼
------解决方案--------------------
调用系统调用后,不妨使用perror来看看出错信息。