micro-utils/src/procps/ps/ps.c

68 lines
1.1 KiB
C

#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h>
int open_file(const char *path) {
int fd = open(path, O_RDONLY);
if (fd < 0) {
fprintf(stderr, "ps: %s: %s\n", path, strerror(errno));
return -1;
}
return fd;
}
int pscan(const char *pid) {
char path[PATH_MAX + 1];
char cmdline[PATH_MAX + 1];
/* Arguments */
snprintf(path, sizeof(path), "/proc/%s/cmdline", pid);
int fd = open_file(path);
if (fd == -1)
return 1;
read(fd, cmdline, sizeof(cmdline));
close(fd);
printf("%5s %5s\n", pid, cmdline);
return 0;
}
int main(int argc, char **argv) {
int opt;
while ((opt = getopt(argc, argv, "o:")) != -1) {
switch (opt) {
case 'o':
break;
default:
printf("ps [o] [PID]\n\t-o Options (nice, tty, cmd, pid, nice)\n");
return 0;
}
}
DIR *dp = opendir("/proc");
if (dp == NULL) {
fprintf(stderr, "ps: /proc: %s\n", strerror(errno));
return 1;
}
printf("PID CMD\n");
int ret = 0;
struct dirent *ep;
while ((ep = readdir(dp)) != NULL)
if (atoi(ep->d_name))
if (pscan(ep->d_name))
ret = 1;
closedir(dp);
return ret;
}