12 char *get_name_by_pid(int pid)
15 static char cmdline[128];
21 if (read_cmdline(pid, pid, cmdline, sizeof(cmdline))) {
26 bname = basename(cmdline);
32 static int parse_pid(DIR **dir)
34 struct dirent *dirent;
38 dirent = readdir(*dir);
46 printf("Failed to read /proc directory: %s\n", strerror(error));
50 if (dirent->d_name[0] < '0' || dirent->d_name[0] > '9')
53 return atoi(dirent->d_name);
56 static int opendir_check(DIR **dir, const char *path)
64 fprintf(stderr, "Failed to open %s directory: %s\n",
65 path, strerror(error));
73 int get_next_tid(int pid, DIR **dir)
78 snprintf(path, sizeof(path), "/proc/%d/task/", pid);
79 if (opendir_check(dir, path))
83 return parse_pid(dir);
86 int get_next_pid(DIR **dir)
88 if (opendir_check(dir, "/proc"))
91 return parse_pid(dir);
94 int get_next_pid_by_name(DIR **dir, char *name)
99 if (opendir_check(dir, "/proc"))
103 pid = parse_pid(dir);
107 pname = get_name_by_pid(pid);
110 if (strcmp(pname, name))
119 int read_cmdline(int pid, int tid, char *cmdline, size_t len)
125 snprintf(path, sizeof(path), "/proc/%d/task/%d/cmdline", pid, tid);
126 file = fopen(path, "rb");
131 ret = fread(cmdline, 1, len, file);
133 cmdline[ret - 1] = 0;
136 return ret > 0 ? 0 : -1;
139 static int pid_is_ok(int pid)
144 snprintf(path, sizeof(path), "/proc/%d/", pid);
146 if (stat(path, &statt))
153 * Test whether a pid string number exists in the system as a pid
156 int pidstr_is_ok(const char *str)
160 /* Test that it is all digits */
161 for (i = 0; i < strlen(str); i++)
162 if (str[i] < '0' || str[i] > '9')
167 return pid_is_ok(pid);