-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpinfo.c
109 lines (94 loc) · 2.88 KB
/
pinfo.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include "shell.h"
#include "utils.h"
#include "pinfo.h"
void handle_pinfo(int argc, char** argv) {
if (argc > 0 && strcmp(argv[argc-1], "&") == 0) {
argc--;
}
if (argc == 0) {
pinfo(-1);
return;
}
if (argc > 1 && argc < 0) {
fprintf(stderr, "Could not list process details: Invalid arguments.\n");
return;
}
int pid = strtol(argv[0], NULL, 10);
if (pid < 0) {
fprintf(stderr, "Could not list process details: Invalid arguments.\n(PS.: Process IDs are non-negative)\n");
return;
}
pinfo(pid);
}
bool pinfo(pid_t pid) {
if (pid < 0) {
pid = getpid();
}
char* stat_path = (char*)malloc(sizeof(char) * (15 + length_num(pid)));
// process ids are >= 0, so length_num works fine (it ignores '-' sign)
sprintf(stat_path, "/proc/%d/status", pid);
char* p_name = (char*)malloc(sizeof(char) * MAX_STATIC_STR_LEN); // should be enough
char p_status;
char* p_mem = (char*)malloc(sizeof(char) * MAX_STATIC_STR_LEN); // should be enough
char* temp = (char*)malloc(sizeof(char) * MAX_STATIC_STR_LEN); // should be enough
FILE* f = fopen(stat_path, "r");
if (f == NULL) {
perror("Could not list process details");
free(temp);
free(p_name);
free(p_mem);
free(stat_path);
return false;
}
int i = 0;
while (fgets(temp, MAX_STATIC_STR_LEN-1, f) != NULL) {
i++;
if (i == 1) {
// Process name
strtok(temp, space_delim);
char* t = strtok(NULL, space_delim);
if (t == NULL)
continue;
strcpy(p_name, t);
} else if (i == 3) {
// Status
strtok(temp, space_delim);
char* t = strtok(NULL, space_delim);
if (t == NULL)
continue;
p_status = t[0];
} else if (i == 18) {
// Virtual memory size
strtok(temp, space_delim);
char* t = strtok(NULL, space_delim);
if (t == NULL)
break;
strcpy(p_mem, t);
t = strtok(NULL, space_delim);
if (t == NULL)
break;
strcat(p_mem, t);
break;
}
}
fclose(f);
sprintf(stat_path, "/proc/%d/exe", pid);
ssize_t exec_len = readlink(stat_path, temp, MAX_STATIC_STR_LEN-1);
if (exec_len < 0) {
perror("Could not list process details");
return false;
}
temp[exec_len] = '\0';
char* p_path = get_relative_pwd(temp);
// All data available
printf("PROCESS: %s\tID: %d\n", p_name, pid);
printf("PROCESS STATUS: %c\n", p_status);
printf("VIRTUAL MEMORY: %s\n", p_mem);
printf("EXECUTABLE PATH: %s\n", p_path);
free(p_path);
free(temp);
free(p_name);
free(p_mem);
free(stat_path);
return true;
}