2 * Copyright (C) 2010 Timo Kokkonen <kaapeli@itanic.dy.fi>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program; if not, write to the Free Software
15 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 #include <sys/types.h>
29 char *get_name_by_pid(int pid)
32 static char cmdline[128];
38 if (read_cmdline(pid, pid, cmdline, sizeof(cmdline))) {
43 bname = basename(cmdline);
49 static int parse_pid(DIR **dir)
51 struct dirent *dirent;
55 dirent = readdir(*dir);
63 printf("Failed to read /proc directory: %s\n", strerror(error));
67 if (dirent->d_name[0] < '0' || dirent->d_name[0] > '9')
70 return atoi(dirent->d_name);
73 static int opendir_check(DIR **dir, const char *path)
81 fprintf(stderr, "Failed to open %s directory: %s\n",
82 path, strerror(error));
90 int get_next_tid(int pid, DIR **dir)
95 snprintf(path, sizeof(path), "/proc/%d/task/", pid);
96 if (opendir_check(dir, path))
100 return parse_pid(dir);
103 int get_next_pid(DIR **dir)
105 if (opendir_check(dir, "/proc"))
108 return parse_pid(dir);
111 int get_next_pid_by_name(DIR **dir, char *name)
116 if (opendir_check(dir, "/proc"))
120 pid = parse_pid(dir);
124 pname = get_name_by_pid(pid);
127 if (strcmp(pname, name))
136 int read_cmdline(int pid, int tid, char *cmdline, size_t len)
142 snprintf(path, sizeof(path), "/proc/%d/task/%d/cmdline", pid, tid);
143 file = fopen(path, "rb");
148 ret = fread(cmdline, 1, len, file);
150 cmdline[ret - 1] = 0;
153 return ret > 0 ? 0 : -1;
156 static int pid_is_ok(int pid)
161 snprintf(path, sizeof(path), "/proc/%d/", pid);
163 if (stat(path, &statt))
170 * Test whether a pid string number exists in the system as a pid
173 int pidstr_is_ok(const char *str)
177 /* Test that it is all digits */
178 for (i = 0; i < strlen(str); i++)
179 if (str[i] < '0' || str[i] > '9')
184 return pid_is_ok(pid);