]>
git.ipfire.org Git - thirdparty/util-linux.git/blob - misc-utils/procs.c
2 * procs.c -- functions to parse the linux /proc filesystem.
3 * (c) 1994 salvatore valente <svalente@mit.edu>
5 * this program is free software. you can redistribute it and
6 * modify it under the terms of the gnu general public license.
7 * there is no warranty.
15 #define _POSIX_SOURCE 1
17 #include <sys/types.h>
27 extern char *mybasename (char *);
28 static char *parse_parens (char *buf
);
31 get_pids (char *process_name
, int get_all
) {
35 char *dname
, fname
[100], *cp
, buf
[256];
39 int pid
, *pids
, num_pids
, pids_size
;
41 dir
= opendir ("/proc");
43 perror ("opendir /proc");
48 num_pids
= pids_size
= 0;
50 while ((ent
= readdir (dir
)) != NULL
) {
52 if (! isdigit (*dname
)) continue;
54 sprintf (fname
, "/proc/%d/cmdline", pid
);
55 /* get the process owner */
56 status
= stat (fname
, &st
);
57 if (status
!= 0) continue;
58 if (! get_all
&& uid
!= st
.st_uid
) continue;
59 /* get the command line */
60 fp
= fopen (fname
, "r");
62 cp
= fgets (buf
, sizeof (buf
), fp
);
64 /* an empty command line means the process is swapped out */
66 /* get the process name from the statfile */
67 sprintf (fname
, "/proc/%d/stat", pid
);
68 fp
= fopen (fname
, "r");
70 cp
= fgets (buf
, sizeof (buf
), fp
);
71 if (cp
== NULL
) continue;
73 cp
= parse_parens (buf
);
74 if (cp
== NULL
) continue;
76 /* ok, we got the process name. */
77 if (strcmp (process_name
, mybasename (cp
))) continue;
78 while (pids_size
< num_pids
+ 2) {
80 pids
= (int *) realloc (pids
, sizeof (int) * pids_size
);
82 pids
[num_pids
++] = pid
;
90 * parse_parens () -- return an index just past the first open paren in
91 * buf, and terminate the string at the matching close paren.
93 static char *parse_parens (char *buf
)
98 cp
= strchr (buf
, '(');
99 if (cp
== NULL
) return NULL
;
102 for (ip
= cp
; *ip
; ip
++) {
116 char *mybasename (char *path
)
120 cp
= strrchr (path
, '/');
121 return (cp
? cp
+ 1 : path
);