c - Linux 驱动程序中的段错误

标签 c linux-kernel segmentation-fault linux-device-driver

我正在尝试编写一个Linux驱动程序。内核版本为2.4.18,发行版为Red Hat linux 8.0。

我的驱动程序的代码是:

#define LINUX

#include <linux/kernel.h> /* We're doing kernel work */
#include <linux/module.h> /* Specifically, a module */
#include <linux/fs.h>
#include <asm-i386/semaphore.h>
#include "rng.h"
#include <linux/random.h>
#include <linux/slab.h>

#define DEVICE_NAME "rng"
#define BUF_LEN 80

static int major;
int init_module();
void cleanup_module();
static int device_open(struct inode *, struct file *);
static int device_release(struct inode *, struct file *);

struct file_operations my_fops = {
  open: device_open,
  release: device_release,
};


/* Init and Cleanup */

int init_module() {
   SET_MODULE_OWNER(&my_fops);
   major = register_chrdev(0, DEVICE_NAME, &my_fops);
   return 0;
}

void cleanup_module() {

   int ret = unregister_chrdev(major, DEVICE_NAME);
   if (ret < 0)
       printk("Error in unregister_chrdev: %d\n", ret);

}

static int device_open(struct inode *inode, struct file *file) {
   file->f_op=&my_fops;
   return 1;
}

static int device_release(struct inode *inode, struct file *file) {
   return 0;
}

我用来测试驱动程序的代码是:

#include <sys/types.h>
#include <errno.h> 
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>

int openTest() {
    int game1 = open("/dev/game1", O_RDONLY); // SEGMENTATION FAULT
    int retValue=1;

    close(game1);
    return retValue;
}

int main() {
    int res;
    if (openTest() < 1) {
       fprintf(stderr, "open didnt work\n");
    return -1;
    }
    fprintf(stderr, "everything works :)\n");
    return 0;
}

在上面的代码中,当我尝试打开设备时遇到段错误。有人可以向我解释为什么我会遇到这个段错误吗?实在是看不懂。

非常感谢!

最佳答案

在 Linux 内核中,如果没有错误,通常会返回 0(零)。您的 device_open() 例程被硬编码为返回 1(一),这可能会导致您的段错误。

This Linux Device Drivers书可能对你有帮助。链接版本是为内核 2.0.x - 2.4.x 编写的,因此该信息应该适合您正在使用的尘土飞扬且古老的内核。

关于c - Linux 驱动程序中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24351735/

相关文章:

c - int 矩阵中的段错误

c - 需要帮助以什么算法方式来解决这个问题

linux - 从文件中的 VMSTAT 中提取 %CPU 使用率

c - 与 C 中的函数 strtok() 作斗争

c++ - 限制每个进程的物理内存

c - 在内核模块中,如何知道给定路径是文件还是目录?

cocoa - Core Data 内部方法崩溃 (SIGSEGV)

c++ - 绘制 Sprite 导致 Segmentation Fault

C自定义malloc函数不读取 block 大小

c++ - `Too many initializers` 用于 RTEMS 驱动程序定义中的阵列设置