415-device-driver/Test/Mohammed_UzairHamed_HW6_main.c
2024-12-08 18:49:17 -08:00

92 lines
2.4 KiB
C

/**************************************************************
* Class:: CSC-415-01 Fall 2024
* Name:: Uzair Hamed Mohammed
* Student ID:: 920142896
* GitHub-Name:: gamersekofy
* Project:: Assignment 6 - Device Driver
*
* File:: Mohammed_UzairHamed_HW6_main.c
*
* Description:: This file contains a very easy to use and application that
reads and writes data
* to the tempMonitor kernel module.
**************************************************************/
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
#include <unistd.h>
#define IOCTL_GET_TEMP _IOR('t', 1, int)
#define GREEN "\033[1;32m"
#define RESET "\033[0m"
void read_temp(int fd, const char *unit) {
char buffer[128];
ssize_t bytes_read;
/* Declare this variable because /sys/class/thermal/thermal_zonex/ isn't
available on virtual machines. In case of a virtual machine, set this flag
that will make the kernel module return a simulated temperature. */
int is_simulated = 0;
// Writing the desired unit or "simulate" command to the device
ssize_t bytes_written = write(fd, unit, strlen(unit));
if (bytes_written < 0) {
return;
}
// Reading the temperature
bytes_read = read(fd, buffer, sizeof(buffer));
if (bytes_read < 0) {
return;
} else {
buffer[bytes_read] = '\0';
// Check if the temperature is simulated. If it is, set flag here.
if (strstr(buffer, "(simulated temperature)") != NULL) {
is_simulated = 1;
}
if (is_simulated) {
printf(GREEN "CPU Temperature\n--- -----------\n" RESET "%s\n", buffer);
} else {
printf(GREEN "CPU Temperature\n--- -----------\n" RESET "%s\n", buffer);
}
}
}
int main() {
int fd;
char choice;
// Access kernel module here
fd = open("/dev/temp_monitor", O_RDWR);
if (fd < 0) {
perror("Failed to open the device");
return -1;
}
// Ask the user for the preferred temperature unit
printf("Choose temperature unit (C/F): ");
scanf(" %c", &choice);
if (choice == 'C' || choice == 'c') {
// Request the kernel module provide temperature in Celsius
read_temp(fd, "C");
} else if (choice == 'F' || choice == 'f') {
// Request the kernel module provide the temperature in Fahrenheit
read_temp(fd, "F");
} else {
printf("Invalid choice. Please choose 'C' or 'F'.\n");
close(fd);
return -1;
}
close(fd);
return 0;
}