blob: 247d79f9f2f7a72f695e08ec1f7c4c0293b1d319 [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
10#include <stdio.h>
11#include <ctype.h>
12#include <string.h>
Eric Andersenaad1a882001-03-16 22:47:14 +000013#include <stdlib.h>
14#include "libbb.h"
15
Eric Andersenaad1a882001-03-16 22:47:14 +000016/* find_pid_by_name()
Eric Andersenc7bda1c2004-03-15 08:29:22 +000017 *
Eric Andersen44608e92002-10-22 12:21:15 +000018 * Modified by Vladimir Oleynik for use with libbb/procps.c
Eric Andersenaad1a882001-03-16 22:47:14 +000019 * This finds the pid of the specified process.
Eric Andersenc7bda1c2004-03-15 08:29:22 +000020 * Currently, it's implemented by rummaging through
Eric Andersenaad1a882001-03-16 22:47:14 +000021 * the proc filesystem.
22 *
23 * Returns a list of all matching PIDs
Bernhard Reutner-Fischer56b21712005-10-06 12:10:48 +000024 * It is the caller's duty to free the returned pidlist.
Eric Andersenaad1a882001-03-16 22:47:14 +000025 */
Denis Vlasenkobe905d52006-09-27 14:17:31 +000026long* find_pid_by_name(const char* pidName)
Eric Andersenaad1a882001-03-16 22:47:14 +000027{
Eric Andersen44608e92002-10-22 12:21:15 +000028 long* pidList;
Denis Vlasenkobe905d52006-09-27 14:17:31 +000029 int i = 0;
30 procps_status_t* p;
Eric Andersenaad1a882001-03-16 22:47:14 +000031
Eric Andersen44608e92002-10-22 12:21:15 +000032 pidList = xmalloc(sizeof(long));
Denis Vlasenkobe905d52006-09-27 14:17:31 +000033 while ((p = procps_scan(0)) != 0) {
Eric Andersen5378fbc2003-08-06 08:22:10 +000034 if (strncmp(p->short_cmd, pidName, COMM_LEN-1) == 0) {
Denis Vlasenkobe905d52006-09-27 14:17:31 +000035 pidList = xrealloc( pidList, sizeof(long) * (i+2));
36 pidList[i++] = p->pid;
Eric Andersenaad1a882001-03-16 22:47:14 +000037 }
38 }
39
Eric Andersen44608e92002-10-22 12:21:15 +000040 pidList[i] = i==0 ? -1 : 0;
Eric Andersenaad1a882001-03-16 22:47:14 +000041 return pidList;
42}
Eric Andersenaad1a882001-03-16 22:47:14 +000043
Rob Landleydfba7412006-03-06 20:47:33 +000044long *pidlist_reverse(long *pidList)
Bernhard Reutner-Fischer56b21712005-10-06 12:10:48 +000045{
Denis Vlasenkobe905d52006-09-27 14:17:31 +000046 int i = 0;
Bernhard Reutner-Fischerab52db82005-10-07 15:44:37 +000047 while (pidList[i] > 0 && ++i);
Denis Vlasenkobe905d52006-09-27 14:17:31 +000048 if (i-- > 0) {
Bernhard Reutner-Fischer56b21712005-10-06 12:10:48 +000049 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}