diff options
author | fadhil riyanto <me@fadev.org> | 2024-08-18 10:27:18 +0700 |
---|---|---|
committer | fadhil riyanto <me@fadev.org> | 2024-08-18 10:27:18 +0700 |
commit | 1b5dd78a4ff7c866b7a21d72bd9245505fe1d826 (patch) | |
tree | 14bbc7eb27948cbf5d138faa34b3f80aa1f19860 | |
parent | 69e75e6e398fc602e80f5de21d2c120e0703dd94 (diff) |
test file
Signed-off-by: fadhil riyanto <me@fadev.org>
-rw-r--r-- | bat0.c | 64 | ||||
-rw-r--r-- | inotify.c | 29 |
2 files changed, 93 insertions, 0 deletions
@@ -0,0 +1,64 @@ +#include <signal.h> +#include <signal.h> +#include <stdlib.h> +#include <unistd.h> +#include <fcntl.h> +#include <string.h> +#include <stdio.h> +#include <sys/stat.h> + +volatile int need_exit = 0; + +static __off_t getfile_size(int fd) +{ + struct stat st; + int ret; + + ret = fstat(fd, &st); + if (ret == -1) { + perror("fstat"); + return -1; + } + + return st.st_size; +} + +static int open_bat0(const char* bat0dir) +{ + return open(bat0dir, O_RDONLY); +} + +static char* read_bat0(int fd) +{ + off_t size = getfile_size(fd); + char *buf = (char*)malloc(size); + memset(buf, '\0', size); + read(fd, buf, size); + return buf; +} + +static int close_bat0(int fd) +{ + return close(fd); +} + +void signal_cb(int signal) +{ + need_exit = 1; +} + +int main() +{ + signal(SIGINT, signal_cb); + + while (!need_exit) { + int fd = open_bat0("/sys/class/power_supply/BAT0/capacity"); + char* bat0data = read_bat0(fd); + + printf("%s\n", bat0data); + free(bat0data); + + close_bat0(fd); + sleep(3); + } +}
\ No newline at end of file diff --git a/inotify.c b/inotify.c new file mode 100644 index 0000000..6059d20 --- /dev/null +++ b/inotify.c @@ -0,0 +1,29 @@ +#include <stdio.h> +#include <unistd.h> +#include <stdlib.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <fcntl.h> + +typedef int FD ; + +int main() { + FD filed = open("/tmp/test_inotify", O_RDWR ); + char buf[128]; + + if( !filed ) { + printf("Openfile error\n"); + exit(-1); + } + + int nbytes; + while(1) { + nbytes = read(filed, buf, 16); + printf("read %d bytes from file.\n", nbytes); + if(nbytes > 0) { + printf("%s\n", buf); // split buffer by new line. + } + sleep(1); + } + return 0; +} |