implement proc status parsing

This commit is contained in:
mykola2312 2024-07-20 17:42:06 +03:00
parent bf3a0ece78
commit e0640a7878
3 changed files with 95 additions and 0 deletions

View file

@ -1,4 +1,33 @@
#ifndef __PROCESS_H #ifndef __PROCESS_H
#define __PROCESS_H #define __PROCESS_H
#include <sys/types.h>
typedef enum {
UNINTERRUPTABLE_SLEEP = 'D',
IDLE_KERNEL_THREAD = 'I',
RUNNING = 'R',
INTERRUPTIBLE_SLEEP = 'S',
STOPPED = 'T',
STOPPED_BY_DEBUGGER = 't',
DEAD = 'X',
ZOMBIE = 'Z'
} process_state_t;
#define MAX_PROCESS_NAME 256
typedef struct {
char name[MAX_PROCESS_NAME];
mode_t umask;
process_state_t state;
pid_t tgid;
pid_t ngid;
pid_t pid;
pid_t ppid;
pid_t tracer_pid;
uid_t uid;
gid_t gid;
} process_status_t;
int process_parse_status(pid_t pid, process_status_t* status);
#endif #endif

View file

@ -3,6 +3,19 @@
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
process_status_t status = {};
process_parse_status(getpid(), &status);
printf("name: %s\n", status.name);
printf("umask: %d\n", status.umask);
printf("state: %d\n", status.state);
printf("tgid: %d\n", status.tgid);
printf("ngid: %d\n", status.ngid);
printf("pid: %d\n", status.pid);
printf("ppid: %d\n", status.ppid);
printf("tracer_pid: %d\n", status.tracer_pid);
printf("uid: %d\n", status.uid);
printf("gid: %d\n", status.gid);
return 0; return 0;
} }

View file

@ -1 +1,54 @@
#include "process.h" #include "process.h"
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int process_parse_status(pid_t pid, process_status_t* status)
{
char statusPath[256] = {0};
snprintf(statusPath, sizeof(statusPath), "/proc/%d/status", pid);
int statusFd = open(statusPath, O_RDONLY);
if (statusFd < 0) return 1;
char buffer[4096] = {0};
int rd = read(statusFd, buffer, sizeof(buffer));
close(statusFd);
if (rd < 1) return 1;
char* lineptr = NULL, *line = strtok_r(buffer, "\n", &lineptr);
while (line != NULL)
{
char* fieldptr = NULL;
const char* key = (const char*)strtok_r(line, ":\t", &fieldptr);
const char* value = (const char*)strtok_r(NULL, ":\t", &fieldptr);
if (!strcmp(key, "Name"))
strncpy(status->name, value, MAX_PROCESS_NAME);
else if (!strcmp(key, "Umask"))
status->umask = (unsigned int)strtoul(value, NULL, 8);
else if (!strcmp(key, "State"))
status->state = (process_state_t)value[0];
else if (!strcmp(key, "Tgid"))
status->tgid = atoi(value);
else if (!strcmp(key, "Ngid"))
status->ngid = atoi(value);
else if (!strcmp(key, "Pid"))
status->pid = atoi(value);
else if (!strcmp(key, "PPid"))
status->ppid = atoi(value);
else if (!strcmp(key, "TracerPid"))
status->tracer_pid = atoi(value);
else if (!strcmp(key, "Uid"))
status->uid = atoi(value);
else if (!strcmp(key, "Gid"))
status->gid = atoi(value);
line = strtok_r(NULL, "\n", &lineptr);
}
return 0;
}