process utilities related style cleanup
[oweals/busybox.git] / libbb / find_pid_by_name.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Utility routines.
4  *
5  * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
6  *
7  * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
8  */
9
10 #include <stdio.h>
11 #include <ctype.h>
12 #include <string.h>
13 #include <stdlib.h>
14 #include "libbb.h"
15
16 /* find_pid_by_name()
17  *
18  *  Modified by Vladimir Oleynik for use with libbb/procps.c
19  *  This finds the pid of the specified process.
20  *  Currently, it's implemented by rummaging through
21  *  the proc filesystem.
22  *
23  *  Returns a list of all matching PIDs
24  *  It is the caller's duty to free the returned pidlist.
25  */
26 long* find_pid_by_name(const char* pidName)
27 {
28         long* pidList;
29         int i = 0;
30         procps_status_t* p;
31
32         pidList = xmalloc(sizeof(long));
33         while ((p = procps_scan(0)) != 0) {
34                 if (strncmp(p->short_cmd, pidName, COMM_LEN-1) == 0) {
35                         pidList = xrealloc( pidList, sizeof(long) * (i+2));
36                         pidList[i++] = p->pid;
37                 }
38         }
39
40         pidList[i] = i==0 ? -1 : 0;
41         return pidList;
42 }
43
44 long *pidlist_reverse(long *pidList)
45 {
46         int i = 0;
47         while (pidList[i] > 0 && ++i);
48         if (i-- > 0) {
49                 long k;
50                 int j;
51                 for (j = 0; i > j; i--, j++) {
52                         k = pidList[i];
53                         pidList[i] = pidList[j];
54                         pidList[j] = k;
55                 }
56         }
57         return pidList;
58 }