-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathps.c
More file actions
69 lines (52 loc) · 1.69 KB
/
ps.c
File metadata and controls
69 lines (52 loc) · 1.69 KB
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
#include <fcntl.h>
#include<string.h>
#include<stdio.h>
#include<unistd.h>
#include<ctype.h>
#include"utils.h"
#include"processes.h"
bool validate_ps(Cmd_s *cmd) {
if (cmd->argc > 2) {
fprintf(stderr, "Usage: pinfo <pid>\n");
return 1;
}
return 0;
}
void ps(Cmd_s *cmd) {
if (validate_ps(cmd)) return;
int pid;
if (cmd->argc == 1) pid = shell_pid;
else pid = atoi(cmd->argv[1]);
char *exe_path = (char *) malloc (MAX_INPUT_SIZE*sizeof(char));
sprintf(exe_path, "/proc/%d/exe", pid);
char *exe = (char *) malloc (MAX_INPUT_SIZE*sizeof(char));
int l = readlink(exe_path, exe, MAX_INPUT_SIZE);
exe[l] = 0;
char *proc_fpath = (char *) malloc (MAX_INPUT_SIZE*sizeof(char));
sprintf(proc_fpath, "/proc/%d/stat", pid);
FILE *fd = fopen(proc_fpath, "r");
int *i = (int *) malloc (sizeof(int));
char *ign = (char *) malloc(MAX_INPUT_SIZE*sizeof(char));
char status;
long int vmem;
char *proc_mempath = (char *) malloc (MAX_INPUT_SIZE*sizeof(char));
sprintf(proc_mempath, "/proc/%d/statm", pid);
fscanf(fd, "%d %s %c %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %ld",
&pid, ign, &status,
i, i, i, i, i, i, i, i, i, i, i, i, i, i, i, i, i, i, i,
&vmem);
char *status_desc;
if (status == 'R') status_desc = "running";
else if (status == 'T' || status == 't') status_desc = "stopped";
else if (status == 'S') status_desc = "sleeping";
else if (status == 'D') status_desc = "waiting";
else if (status == 'Z') status_desc = "zombie";
else status_desc = "other";
fprintf(stdout, "pid: %d\n", pid);
fprintf(stdout, "status: %s\n", status_desc);
fprintf(stdout, "memory: %ld\n", vmem);
fprintf(stdout, "executable: %s\n", exe);
fclose(fd);
free(i);
free(ign);
}