diff options
author | PA4WDH | 2023-05-20 17:17:43 +0200 |
---|---|---|
committer | PA4WDH | 2023-05-20 17:17:43 +0200 |
commit | 15d9095122c0d4f9a4dab05fb0e84d84c624e1b4 (patch) | |
tree | c6edcc0b2efe1dc68577d57de9de74ae4bf8cdd4 /sysfs.c | |
parent | Initial commit, POC shell script (diff) | |
download | cputemp2maxfreq-15d9095122c0d4f9a4dab05fb0e84d84c624e1b4.tar.gz cputemp2maxfreq-15d9095122c0d4f9a4dab05fb0e84d84c624e1b4.tar.bz2 cputemp2maxfreq-15d9095122c0d4f9a4dab05fb0e84d84c624e1b4.zip |
Translate POC to C code0.1
Diffstat (limited to 'sysfs.c')
-rw-r--r-- | sysfs.c | 83 |
1 files changed, 83 insertions, 0 deletions
@@ -0,0 +1,83 @@ +#include <stdio.h> +#include <fcntl.h> +#include <unistd.h> +#include <stdlib.h> +#include <string.h> +#include "debug.h" + +int sysfs_read_str(char *sysfs_file,char *buf,size_t bufsize) +{ + int sysfs_handle; + size_t datalen; + + DEBUG1_SYSFS("Reading sysfs file %s\n",sysfs_file); + +// Open the file + sysfs_handle=open(sysfs_file,O_RDONLY); + DEBUG2_SYSFS("Open returned %d\n",sysfs_handle); + if (sysfs_handle<0) return -1; + +// Read the content of the file + datalen=read(sysfs_handle,buf,bufsize); + HEXDUMP2_SYSFS(buf,datalen); + close(sysfs_handle); + buf[datalen]=0; + +// Strip newline + if (buf[datalen-1]=='\n') + { + DEBUG2_SYSFS("Newline stripped\n"); + datalen--; + buf[datalen]=0; + } + + return datalen; +} + +long int sysfs_read_long_int(char *sysfs_file) +{ + char buf[255]; + int datalen; + +// Read data + datalen=sysfs_read_str(sysfs_file,buf,sizeof(buf)); + if (datalen<0) return 0; + +// Convert to long int + return strtoll((char*)&buf,NULL,10); +} + +int sysfs_write_str(char *sysfs_file,char *value,int checkdelay) +{ + int sysfs_handle; + size_t len; + char buf[255]; + + DEBUG1_SYSFS("Writing %s to sysfs file %s\n",value,sysfs_file); + +// Open the file + sysfs_handle=open(sysfs_file,O_WRONLY); + DEBUG2_SYSFS("Open returned %d\n",sysfs_handle); + if (sysfs_handle<0) return -1; + +// Write the data + len=write(sysfs_handle,value,strlen(value)); + close(sysfs_handle); + DEBUG2_SYSFS("Written %zd bytes\n",len); + +// What if instructed to + if (checkdelay>0) usleep(checkdelay*1000); + +// Validate we actually set what we want to set + sysfs_read_str(sysfs_file,buf,sizeof(buf)); + DEBUG2_SYSFS("Content is now %s\n",buf); + + if (strncmp(value,buf,255)!=0) + { + DEBUG2_SYSFS("Set failed\n"); + return -1; + } + DEBUG2_SYSFS("Set successfull\n"); + + return 0; +} |