简体   繁体   English

Linux驱动程序中的分段错误

[英]Segmentation fault in linux driver

I'm trying to write a linux driver. 我正在尝试编写Linux驱动程序。 The kernel version is 2.4.18 and the distribution is Red Hat linux 8.0. 内核版本为2.4.18,发行版本为Red Hat linux 8.0。

The code of my driver is: 我的驱动程序代码是:

#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;
}

And the code I'm using in order to test my driver is: 我用来测试驱动程序的代码是:

#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;
}

In the code above, I'm getting a segmentation fault when I'm trying to open the device. 在上面的代码中,当我尝试打开设备时遇到分段错误。 Can somebody explain to me why I'm getting this segmentation fault? 有人可以向我解释为什么我会遇到这种细分错误吗? I really don't understand. 我真的不明白

Thanks a lot! 非常感谢!

In Linux kernel land, it is convention to return a 0 (zero) when there are no errors. 在Linux内核领域中,通常在没有错误的情况下返回0(零)。 Your device_open() routine is hardcoded to return a 1 (one), which may be causing your segfault. 您的device_open()例程经过硬编码以返回1(一),这可能会导致您的段错误。

This Linux Device Drivers book may be helpful to you. 这本《 Linux设备驱动程序》手册可能对您有所帮助。 The linked edition is written for kernel 2.0.x - 2.4.x, so the information should be appropriate for the dusty and ancient kernel you are using. 链接版本是针对内核2.0.x-2.4.x编写的,因此该信息应适用于您所使用的尘土飞扬的古老内核。

This line seems to be wrong file->f_op=&my_fops; 这行似乎是错误的file->f_op=&my_fops;

Basically when writing a linux driver operations are setup at build time itself. 基本上,在编写linux驱动程序时,操作本身是在构建时设置的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM