blob: e98616940c061ce28b9a62d74203ae7ac13fd590 [file] [log] [blame]
Eric Andersenaad1a882001-03-16 22:47:14 +00001/* vi: set sw=4 ts=4: */
2/*
3 * Utility routines.
4 *
Eric Andersenc7bda1c2004-03-15 08:29:22 +00005 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Eric Andersenaad1a882001-03-16 22:47:14 +00006 *
Bernhard Reutner-Fischer7fee0c42006-09-13 16:39:19 +00007 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
Eric Andersenaad1a882001-03-16 22:47:14 +00008 */
9
Eric Andersenaad1a882001-03-16 22:47:14 +000010#include "libbb.h"
11
Eric Andersenaad1a882001-03-16 22:47:14 +000012/* find_pid_by_name()
Eric Andersenc7bda1c2004-03-15 08:29:22 +000013 *
Eric Andersen44608e92002-10-22 12:21:15 +000014 * Modified by Vladimir Oleynik for use with libbb/procps.c
Eric Andersenaad1a882001-03-16 22:47:14 +000015 * This finds the pid of the specified process.
Eric Andersenc7bda1c2004-03-15 08:29:22 +000016 * Currently, it's implemented by rummaging through
Eric Andersenaad1a882001-03-16 22:47:14 +000017 * the proc filesystem.
18 *
19 * Returns a list of all matching PIDs
Bernhard Reutner-Fischer56b21712005-10-06 12:10:48 +000020 * It is the caller's duty to free the returned pidlist.
Eric Andersenaad1a882001-03-16 22:47:14 +000021 */
Denis Vlasenko35fb5122006-11-01 09:16:49 +000022pid_t* find_pid_by_name(const char* procName)
Eric Andersenaad1a882001-03-16 22:47:14 +000023{
Denis Vlasenko35fb5122006-11-01 09:16:49 +000024 pid_t* pidList;
Denis Vlasenkobe905d52006-09-27 14:17:31 +000025 int i = 0;
Denis Vlasenko459e4d62006-11-05 00:43:51 +000026 procps_status_t* p = NULL;
Eric Andersenaad1a882001-03-16 22:47:14 +000027
Denis Vlasenko35fb5122006-11-01 09:16:49 +000028 pidList = xmalloc(sizeof(*pidList));
Denis Vlasenko459e4d62006-11-05 00:43:51 +000029 while ((p = procps_scan(p, PSSCAN_PID|PSSCAN_COMM))) {
30 if (strncmp(p->comm, procName, sizeof(p->comm)-1) == 0) {
Denis Vlasenko35fb5122006-11-01 09:16:49 +000031 pidList = xrealloc(pidList, sizeof(*pidList) * (i+2));
Denis Vlasenkobe905d52006-09-27 14:17:31 +000032 pidList[i++] = p->pid;
Eric Andersenaad1a882001-03-16 22:47:14 +000033 }
34 }
35
Denis Vlasenko35fb5122006-11-01 09:16:49 +000036 pidList[i] = 0;
Eric Andersenaad1a882001-03-16 22:47:14 +000037 return pidList;
38}
Eric Andersenaad1a882001-03-16 22:47:14 +000039
Denis Vlasenko35fb5122006-11-01 09:16:49 +000040pid_t *pidlist_reverse(pid_t *pidList)
Bernhard Reutner-Fischer56b21712005-10-06 12:10:48 +000041{
Denis Vlasenkobe905d52006-09-27 14:17:31 +000042 int i = 0;
Denis Vlasenko35fb5122006-11-01 09:16:49 +000043 while (pidList[i])
44 i++;
45 if (--i >= 0) {
46 pid_t k;
Bernhard Reutner-Fischer56b21712005-10-06 12:10:48 +000047 int j;
48 for (j = 0; i > j; i--, j++) {
49 k = pidList[i];
50 pidList[i] = pidList[j];
51 pidList[j] = k;
52 }
53 }
54 return pidList;
55}