我正在尝试编写一个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/