blob: 52e9ee383e962711868c37088a9fc082a8c5b73f [file] [log] [blame]
bigbiff bigbiffe60683a2013-02-22 20:55:50 -05001/*
2 * Copyright (C) 2011 Davidlohr Bueso <dave@gnu.org>
3 *
4 * procutils.c: General purpose procfs parsing utilities
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU Library Public License as published by
8 * the Free Software Foundation; either version 2, or (at your option)
9 * any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Library Public License for more details.
15 */
16
17#include <stdio.h>
18#include <stdlib.h>
19#include <string.h>
20#include <errno.h>
21#include <sys/types.h>
22#include <dirent.h>
23#include <ctype.h>
24
25#include "procutils.h"
26#include "c.h"
27
28/*
29 * @pid: process ID for which we want to obtain the threads group
30 *
31 * Returns: newly allocated tasks structure
32 */
33struct proc_tasks *proc_open_tasks(pid_t pid)
34{
35 struct proc_tasks *tasks;
36 char path[PATH_MAX];
37
38 sprintf(path, "/proc/%d/task/", pid);
39
40 tasks = malloc(sizeof(struct proc_tasks));
41 if (tasks) {
42 tasks->dir = opendir(path);
43 if (tasks->dir)
44 return tasks;
45 }
46
47 free(tasks);
48 return NULL;
49}
50
51/*
52 * @tasks: allocated tasks structure
53 *
54 * Returns: nothing
55 */
56void proc_close_tasks(struct proc_tasks *tasks)
57{
58 if (tasks && tasks->dir)
59 closedir(tasks->dir);
60 free(tasks);
61}
62
63/*
64 * @tasks: allocated task structure
65 * @tid: [output] one of the thread IDs belonging to the thread group
66 * If when an error occurs, it is set to 0.
67 *
68 * Returns: 0 on success, 1 on end, -1 on failure or no more threads
69 */
70int proc_next_tid(struct proc_tasks *tasks, pid_t *tid)
71{
72 struct dirent *d;
73 char *end;
74
75 if (!tasks || !tid)
76 return -1;
77
78 *tid = 0;
79 errno = 0;
80
81 do {
82 d = readdir(tasks->dir);
83 if (!d)
84 return errno ? -1 : 1; /* error or end-of-dir */
85
86 if (!isdigit((unsigned char) *d->d_name))
87 continue;
88
89 *tid = (pid_t) strtol(d->d_name, &end, 10);
90 if (errno || d->d_name == end || (end && *end))
91 return -1;
92
93 } while (!*tid);
94
95 return 0;
96}
97
98#ifdef TEST_PROGRAM
99
100int main(int argc, char *argv[])
101{
102 pid_t tid, pid;
103 struct proc_tasks *ts;
104
105 if (argc != 2) {
106 fprintf(stderr, "usage: %s <pid>\n", argv[0]);
107 return EXIT_FAILURE;
108 }
109
110 pid = strtol(argv[1], (char **) NULL, 10);
111 printf("PID=%d, TIDs:", pid);
112
113 ts = proc_open_tasks(pid);
114 if (!ts)
115 err(EXIT_FAILURE, "open list of tasks failed");
116
117 while (proc_next_tid(ts, &tid) == 0)
118 printf(" %d", tid);
119
120 printf("\n");
121 proc_close_tasks(ts);
122 return EXIT_SUCCESS;
123}
124#endif /* TEST_PROGRAM */