blob: 73467446f31965d6c7a7447fad329cb3a4e0ca49 [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-Fischer56b21712005-10-06 12:10:48 +00007 * Licensed under the GPL v2, 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 */
Rob Landleydfba7412006-03-06 20:47:33 +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;
Eric Andersenaad1a882001-03-16 22:47:14 +000029 int i=0;
Eric Andersen44608e92002-10-22 12:21:15 +000030 procps_status_t * p;
Eric Andersenaad1a882001-03-16 22:47:14 +000031
Eric Andersen44608e92002-10-22 12:21:15 +000032 pidList = xmalloc(sizeof(long));
Bernhard Reutner-Fischer56b21712005-10-06 12:10:48 +000033 while ((p = procps_scan(0)) != 0)
Rob Landley60158cb2005-05-03 06:25:50 +000034 {
Eric Andersen5378fbc2003-08-06 08:22:10 +000035 if (strncmp(p->short_cmd, pidName, COMM_LEN-1) == 0) {
Eric Andersenb24d6562001-12-06 14:52:32 +000036 pidList=xrealloc( pidList, sizeof(long) * (i+2));
Eric Andersen44608e92002-10-22 12:21:15 +000037 pidList[i++]=p->pid;
Eric Andersenaad1a882001-03-16 22:47:14 +000038 }
39 }
40
Eric Andersen44608e92002-10-22 12:21:15 +000041 pidList[i] = i==0 ? -1 : 0;
Eric Andersenaad1a882001-03-16 22:47:14 +000042 return pidList;
43}
Eric Andersenaad1a882001-03-16 22:47:14 +000044
Rob Landleydfba7412006-03-06 20:47:33 +000045long *pidlist_reverse(long *pidList)
Bernhard Reutner-Fischer56b21712005-10-06 12:10:48 +000046{
47 int i=0;
Bernhard Reutner-Fischerab52db82005-10-07 15:44:37 +000048 while (pidList[i] > 0 && ++i);
Bernhard Reutner-Fischer56b21712005-10-06 12:10:48 +000049 if ( i-- > 0) {
50 long k;
51 int j;
52 for (j = 0; i > j; i--, j++) {
53 k = pidList[i];
54 pidList[i] = pidList[j];
55 pidList[j] = k;
56 }
57 }
58 return pidList;
59}