Clean ps command code.

This commit is contained in:
Enrico Fraccaroli (Galfurian)
2023-08-11 13:28:36 -04:00
parent cd6f876fa8
commit 23f2a036e7
+8 -56
View File
@@ -46,13 +46,15 @@ static inline void __iterate_proc_dirs(int proc_fd)
exit(EXIT_FAILURE);
}
// Skip non-directories.
if (dent.d_type != DT_DIR)
if (dent.d_type != DT_DIR) {
continue;
}
// Build the path to the stat file (i.e., `/proc/<pid>/stat`).
strcpy(absolute_path + 6, dent.d_name);
strcat(absolute_path, "/stat");
// Open the `/proc/<pid>/stat` file.
if ((stat_fd = open(absolute_path, O_RDONLY, 0)) == -1) {
stat_fd = open(absolute_path, O_RDONLY, 0);
if (stat_fd == -1) {
continue;
}
// Reset the stat buffer.
@@ -84,60 +86,10 @@ int main(int argc, char **argv)
if (fd == -1) {
perror("ps: cannot access '/proc' folder");
return EXIT_FAILURE;
} else {
printf(FORMAT_S, "PID", "PPID", "STATUS", "CMD");
__iterate_proc_dirs(fd);
close(fd);
}
#if 0
DIR *dir;
struct dirent_t *ent;
int i, fd_self, fd;
unsigned long time, stime;
char flag, *tty;
char cmd[256], tty_self[256], path[256], time_s[256];
FILE *file;
dir = opendir("/proc");
fd_self = open("/proc/self/fd/0", O_RDONLY);
sprintf(tty_self, "%s", ttyname(fd_self));
printf(FORMAT, "PID", "TTY", "TIME", "CMD");
while ((ent = readdir(dir)) != NULL) {
flag = 1;
for (i = 0; ent->d_name[i]; i++)
if (!isdigit(ent->d_name[i])) {
flag = 0;
break;
}
if (flag) {
sprintf(path, "/proc/%s/fd/0", ent->d_name);
fd = open(path, O_RDONLY);
tty = ttyname(fd);
if (tty && strcmp(tty, tty_self) == 0) {
sprintf(path, "/proc/%s/stat", ent->d_name);
file = fopen(path, "r");
fscanf(file, "%d%s%c%c%c", &i, cmd, &flag, &flag, &flag);
cmd[strlen(cmd) - 1] = '\0';
for (i = 0; i < 11; i++)
fscanf(file, "%lu", &time);
fscanf(file, "%lu", &stime);
time = (int)((double)(time + stime) / sysconf(_SC_CLK_TCK));
sprintf(time_s, "%02lu:%02lu:%02lu",
(time / 3600) % 3600, (time / 60) % 60, time % 60);
printf(FORMAT, ent->d_name, tty + 5, time_s, cmd + 1);
fclose(file);
}
close(fd);
}
}
close(fd_self);
#endif
printf(FORMAT_S, "PID", "PPID", "STATUS", "CMD");
__iterate_proc_dirs(fd);
close(fd);
putchar('\n');
return EXIT_SUCCESS;
}