[PATCH 1/2] tools/lib/api/fs: Add procfs int read/write helpers

From: Borislav Petkov
Date: Mon Feb 06 2017 - 20:09:39 EST


From: Borislav Petkov <bp@xxxxxxx>

Add helper functions to be able to read/write ints into proc files.

Signed-off-by: Borislav Petkov <bp@xxxxxxx>
---
tools/lib/api/fs/fs.c | 42 ++++++++++++++++++++++++++++++++++++++++++
tools/lib/api/fs/fs.h | 3 +++
2 files changed, 45 insertions(+)

diff --git a/tools/lib/api/fs/fs.c b/tools/lib/api/fs/fs.c
index 4b6bfc43cccf..8e4b9fe18b75 100644
--- a/tools/lib/api/fs/fs.c
+++ b/tools/lib/api/fs/fs.c
@@ -314,6 +314,22 @@ int filename__read_int(const char *filename, int *value)
return err;
}

+int filename__write_int(const char *filename, int value)
+{
+ char line[64];
+ int fd = open(filename, O_WRONLY), err = -1;
+
+ if (fd < 0)
+ return -1;
+
+ snprintf(line, sizeof(int), "%d", value);
+
+ err = write(fd, line, strnlen(line, 64));
+
+ close(fd);
+ return err;
+}
+
/*
* Parses @value out of @filename with strtoull.
* By using 0 for base, the strtoull detects the
@@ -400,6 +416,32 @@ int procfs__read_str(const char *entry, char **buf, size_t *sizep)
return filename__read_str(path, buf, sizep);
}

+int procfs__read_int(const char *entry, int *value)
+{
+ char path[PATH_MAX];
+ const char *procfs = procfs__mountpoint();
+
+ if (!procfs)
+ return -1;
+
+ snprintf(path, sizeof(path), "%s/%s", procfs, entry);
+
+ return filename__read_int(path, value);
+}
+
+int procfs__write_int(const char *entry, int value)
+{
+ char path[PATH_MAX];
+ const char *procfs = procfs__mountpoint();
+
+ if (!procfs)
+ return -1;
+
+ snprintf(path, sizeof(path), "%s/%s", procfs, entry);
+
+ return filename__write_int(path, value);
+}
+
int sysfs__read_ull(const char *entry, unsigned long long *value)
{
char path[PATH_MAX];
diff --git a/tools/lib/api/fs/fs.h b/tools/lib/api/fs/fs.h
index 6b332dc74498..095f25d4c70f 100644
--- a/tools/lib/api/fs/fs.h
+++ b/tools/lib/api/fs/fs.h
@@ -28,9 +28,12 @@ FS(bpf_fs)


int filename__read_int(const char *filename, int *value);
+int filename__write_int(const char *filename, int value);
int filename__read_ull(const char *filename, unsigned long long *value);
int filename__read_str(const char *filename, char **buf, size_t *sizep);

+int procfs__read_int(const char *entry, int *value);
+int procfs__write_int(const char *entry, int value);
int procfs__read_str(const char *entry, char **buf, size_t *sizep);

int sysctl__read_int(const char *sysctl, int *value);
--
2.11.0


--
Regards/Gruss,
Boris.

Good mailing practices for 400: avoid top-posting and trim the reply.