util: kernel: Add functions for getting procfs stat fields 20/272420/2
authorDongwoo Lee <dwlee08@gmail.com>
Mon, 14 Mar 2022 09:33:54 +0000 (02:33 -0700)
committerDongwoo Lee <dwoo08.lee@samsung.com>
Thu, 17 Mar 2022 03:39:51 +0000 (12:39 +0900)
This adds new functions for getting procfs stat fields of certain
process id as like below prototype:

int kernel_get_process_stat_fields(pid_t pid, char *buffer, int buf_len, char **stat_fields)
 - pid: target process id
 - buffer: string buffer for retrieving procfs stat, each field of
           stat_fileds points out some index within this buffer area.
   Thus, life time of stat_fields are determined by this.
 - buf_len: length of provided buffer
 - stat_fields: string array of retrieved fields, this should be
  declared as (char *)[PROCESS_STAT_FIELD_MAX] type.

Signed-off-by: Dongwoo Lee <dwlee08@gmail.com>
Change-Id: I23008751fdd17ddd17d9e756e1f0d7394bee5f98

include/util/kernel.h
src/util/kernel.c

index f268e93..9846466 100644 (file)
@@ -34,6 +34,15 @@ struct cpu_stat {
        int64_t soft_irq;
 };
 
+enum {
+       PROCESS_STAT_FIELD_PID,
+       PROCESS_STAT_FIELD_COMM,
+       PROCESS_STAT_FIELD_STATE,
+       PROCESS_STAT_FIELD_PPID,
+       PROCESS_STAT_FIELD_PGID,
+       PROCESS_STAT_FIELD_MAX,
+};
+
 int kernel_get_online_cpu_num(void);
 int kernel_get_possible_cpu_num(void);
 
@@ -43,4 +52,7 @@ int kernel_get_per_cpu_stat(struct cpu_stat *cpus, int num_possible_cpus,
 
 int kernel_get_memory_info(const char *key, u_int64_t *val);
 int kernel_get_memory_total(u_int64_t *val);
+
+int kernel_get_process_stat_fields(pid_t pid, char *buffer, int buf_len,
+                                  char *stat_fields[PROCESS_STAT_FIELD_MAX]);
 #endif
index b01594b..3eae652 100644 (file)
@@ -210,3 +210,31 @@ int kernel_get_memory_total(u_int64_t *val)
 
        return 0;
 }
+
+int kernel_get_process_stat_fields(pid_t pid, char *buffer, int buf_len,
+                                  char *stat_fields[PROCESS_STAT_FIELD_MAX])
+{
+       char path[BUFF_MAX];
+       char *pbuffer;
+       FILE *fd;
+       int i;
+
+       snprintf(path, BUFF_MAX, "/proc/%d/stat", pid);
+
+       fd = fopen(path, "r");
+       if (!fd) {
+               _E("failed to open process %d stat", pid);
+               return -EIO;
+       }
+
+       pbuffer = fgets(buffer, buf_len, fd);
+       if (!pbuffer) {
+               _E("failed to read process %d stat", pid);
+               return -EIO;
+       }
+
+       for (i = 0; i < PROCESS_STAT_FIELD_MAX; i++)
+               stat_fields[i] = strsep(&pbuffer, " ");
+
+       return 0;
+}