4

我有一个问题困扰了我一周。我希望有人能帮助我。我写了一个简单的 char 设备模块,它insmod在内核和. 之后我可以看到它。但是当我打开这个 char 设备文件时出现错误。mknod/devinsmodcat /proc/devices

我的字符设备代码是:

#include <linux/module.h>
#include <linux/types.h>
#include <linux/fs.h>
#include <linux/errno.h>
#include <linux/mm.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/cdev.h>
#include <asm/io.h>
#include <asm/system.h>
#include <asm/uaccess.h>
#define CALL_DEV_NAME  "mn2"
#define CALL_DEV_MAJOR 230
struct cdev cdev;
MODULE_LICENSE("GPL");

int call_open(struct inode *inode,struct file *filp){
    int num=MINOR(inode->i_rdev);
    printk("call open minor is:%d \n",num);
    return 0;
}


static struct file_operations call_fops={
    .owner=THIS_MODULE,
    .open=call_open,
};

int call_init(void){
    int result;
    printk("call call_init \n");
    result=register_chrdev_region(MKDEV(CALL_DEV_MAJOR,0),
        1,CALL_DEV_NAME);
    if(result<0){
        printk("registerfail \n");
        return result;
    }
    cdev_init(&cdev,&call_fops);
    cdev.ops=&call_fops;
    cdev.owner=THIS_MODULE;
    cdev_add(&cdev,MKDEV(CALL_DEV_MAJOR,0),1);
    return 0;
}

void call_exit(void){
    printk("call call_exit \n");
    unregister_chrdev(CALL_DEV_MAJOR,CALL_DEV_NAME);
}

module_init(call_init);
module_exit(call_exit);

测试代码是:

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

int main(){
    FILE *fd;
    fd=fopen("/dev/mn2","r+");

    if(fd==NULL)
    printf("fail\n");
    }

我的 Makefile 是:

ifneq ($(KERNELRELEASE),)
obj-m := mn2.o
else
KDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)

all:
    $(MAKE) -C $(KDIR) M=$(PWD) modules
clean:
    rm -f *.ko *.o *.mod.o *.mod.c *.symvers *.order
endif

我使用的命令是:

make
insmod mn2.ko

mn2然后我可以看到/proc/devices

mknod mn2 c 230 0

还有一个文件mn2如下/dev

但是在我编译 test.cgcc test.c -o test并运行测试之后,我总是得到一个fail世界。

你能帮我找出我的错误吗?

4

1 回答 1

1

用这个:

fprintf(stderr, "fopen() failed: %s\n", strerror(errno));

包括一个文件<errno.h>。它将为您提供有关错误的详细信息。我认为它的权限问题。尝试使用 sudo 运行您的用户空间二进制文件。

于 2013-01-31T11:46:49.133 回答