temp-monitor/Module/tempMonitor.c
2024-12-05 22:36:41 -08:00

82 lines
2.5 KiB
C

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#include <linux/ioctl.h>
#include <linux/device.h>
#define DEVICE_NAME "temp_monitor"
#define IOCTL_GET_TEMP _IOR('t', 1, int)
static int temp = 0;
static int major_number;
static struct class* temp_monitor_class = NULL;
static struct device* temp_monitor_device = NULL;
static int device_open(struct inode *inode, struct file *file) {
return 0;
}
static int device_release(struct inode *inode, struct file *file) {
return 0;
}
static long device_ioctl(struct file *file, unsigned int cmd, unsigned long arg) {
switch (cmd) {
case IOCTL_GET_TEMP:
// Simulate reading temperature
temp = 50; // Example temperature
if (copy_to_user((int *)arg, &temp, sizeof(temp))) {
return -EACCES;
}
break;
default:
return -EINVAL;
}
return 0;
}
static struct file_operations fops = {
.open = device_open,
.release = device_release,
.unlocked_ioctl = device_ioctl,
};
static int __init temp_monitor_init(void) {
major_number = register_chrdev(0, DEVICE_NAME, &fops);
if (major_number < 0) {
printk(KERN_ALERT "temp_monitor: Failed to register a major number\n");
return major_number;
}
temp_monitor_class = class_create(THIS_MODULE, DEVICE_NAME);
if (IS_ERR(temp_monitor_class)) {
unregister_chrdev(major_number, DEVICE_NAME);
printk(KERN_ALERT "temp_monitor: Failed to register device class\n");
return PTR_ERR(temp_monitor_class);
}
temp_monitor_device = device_create(temp_monitor_class, NULL, MKDEV(major_number, 0), NULL, DEVICE_NAME);
if (IS_ERR(temp_monitor_device)) {
class_destroy(temp_monitor_class);
unregister_chrdev(major_number, DEVICE_NAME);
printk(KERN_ALERT "temp_monitor: Failed to create the device\n");
return PTR_ERR(temp_monitor_device);
}
printk(KERN_INFO "temp_monitor: Device initialized\n");
return 0;
}
static void __exit temp_monitor_exit(void) {
device_destroy(temp_monitor_class, MKDEV(major_number, 0));
class_unregister(temp_monitor_class);
class_destroy(temp_monitor_class);
unregister_chrdev(major_number, DEVICE_NAME);
printk(KERN_INFO "temp_monitor: Device removed\n");
}
module_init(temp_monitor_init);
module_exit(temp_monitor_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("A CPU Temperature Monitoring Kernel Module");