1 /* vi: set sw=4 ts=4: */
5 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
7 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
12 In Linux we have three ways to determine "process name":
13 1. /proc/PID/stat has "...(name)...", among other things. It's so-called "comm" field.
14 2. /proc/PID/cmdline's first NUL-terminated string. It's argv[0] from exec syscall.
15 3. /proc/PID/exe symlink. Points to the running executable file.
23 comm: first 15 chars of base name
24 (if executable is a symlink, then first 15 chars of symlink name are used)
25 cmdline: argv[0] from exec syscall
26 exe: points to executable (resolves symlink, unlike comm)
28 script (an executable with #!/path/to/interpreter):
29 comm: first 15 chars of script's base name (symlinks are not resolved)
30 cmdline: /path/to/interpreter (symlinks are not resolved)
31 (script name is in argv[1], args are pushed into argv[2] etc)
32 exe: points to interpreter's executable (symlinks are resolved)
34 If FEATURE_PREFER_APPLETS=y (and more so if FEATURE_SH_STANDALONE=y),
35 some commands started from busybox shell, xargs or find are started by
36 execXXX("/proc/self/exe", applet_name, params....)
37 and therefore comm field contains "exe".
40 static int comm_match(procps_status_t *p, const char *procName)
45 if (strncmp(p->comm, procName, 15) != 0)
46 return 0; /* comm does not match */
48 /* In Linux, if comm is 15 chars, it is truncated.
49 * (or maybe the name was exactly 15 chars, but there is
50 * no way to know that) */
51 if (p->comm[14] == '\0')
52 return 1; /* comm is not truncated - matches */
54 /* comm is truncated, but first 15 chars match.
55 * This can be crazily_long_script_name.sh!
56 * The telltale sign is basename(argv[1]) == procName */
61 argv1idx = strlen(p->argv0) + 1;
62 if (argv1idx >= p->argv_len)
64 argv1 = p->argv0 + argv1idx;
66 if (strcmp(bb_basename(argv1), procName) != 0)
72 /* This finds the pid of the specified process.
73 * Currently, it's implemented by rummaging through
74 * the proc filesystem.
76 * Returns a list of all matching PIDs
77 * It is the caller's duty to free the returned pidlist.
79 * Modified by Vladimir Oleynik for use with libbb/procps.c
81 pid_t* FAST_FUNC find_pid_by_name(const char *procName)
85 procps_status_t* p = NULL;
87 pidList = xzalloc(sizeof(*pidList));
88 while ((p = procps_scan(p, PSSCAN_PID|PSSCAN_COMM|PSSCAN_ARGVN|PSSCAN_EXE))) {
89 if (comm_match(p, procName)
90 /* or we require argv0 to match (essential for matching reexeced /proc/self/exe)*/
91 || (p->argv0 && strcmp(bb_basename(p->argv0), procName) == 0)
92 /* or we require /proc/PID/exe link to match */
93 || (p->exe && strcmp(bb_basename(p->exe), procName) == 0)
95 pidList = xrealloc_vector(pidList, 2, i);
96 pidList[i++] = p->pid;
104 pid_t* FAST_FUNC pidlist_reverse(pid_t *pidList)
112 for (j = 0; i > j; i--, j++) {
114 pidList[i] = pidList[j];