1 /* vi: set sw=4 ts=4: */
3 * Mini pgrep/pkill implementation for busybox
5 * Copyright (C) 2007 Loic Grenie <loic.grenie@gmail.com>
7 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
12 /* Idea taken from kill.c */
13 #define pgrep (ENABLE_PGREP && applet_name[1] == 'g')
14 #define pkill (ENABLE_PKILL && applet_name[1] == 'k')
18 OPTBIT_V = 0, /* must be first, we need OPT_INVERT = 0/1 */
28 #define OPT_INVERT (opt & (1 << OPTBIT_V))
29 #define OPT_LIST (opt & (1 << OPTBIT_L))
30 #define OPT_FULL (opt & (1 << OPTBIT_F))
31 #define OPT_ANCHOR (opt & (1 << OPTBIT_X))
32 #define OPT_FIRST (opt & (1 << OPTBIT_O))
33 #define OPT_LAST (opt & (1 << OPTBIT_N))
34 #define OPT_SID (opt & (1 << OPTBIT_S))
35 #define OPT_PPID (opt & (1 << OPTBIT_P))
37 static void act(unsigned pid, char *cmd, int signo)
40 if (option_mask32 & (1 << OPTBIT_L)) /* OPT_LIST */
41 printf("%d %s\n", pid, cmd);
48 int pgrep_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
49 int pgrep_main(int argc UNUSED_PARAM, char **argv)
56 int sid2match, ppid2match;
58 procps_status_t *proc;
59 /* These are initialized to 0 */
62 regmatch_t re_match[1];
64 #define re_buffer (Z.re_buffer)
65 #define re_match (Z.re_match )
67 memset(&Z, 0, sizeof(Z));
69 /* Parse -SIGNAL for pkill. Must be first option, if present */
71 if (pkill && argv[1] && argv[1][0] == '-') {
72 int temp = get_signum(argv[1]+1);
79 /* Parse remaining options */
82 opt_complementary = "s+:P+"; /* numeric opts */
83 opt = getopt32(argv, "vlfxons:P:", &sid2match, &ppid2match);
86 if (pkill && OPT_LIST) { /* -l: print the whole signal list */
93 sid2match = getsid(pid);
95 scan_mask = PSSCAN_COMM | PSSCAN_ARGV0;
97 scan_mask |= PSSCAN_ARGVN;
99 /* One pattern is required, if no -s and no -P */
100 if ((sid2match & ppid2match) < 0 && (!argv[0] || argv[1]))
104 xregcomp(&re_buffer, argv[0], 0);
109 while ((proc = procps_scan(proc, scan_mask)) != NULL) {
112 if (proc->pid == pid)
119 int i = proc->argv_len;
121 if ((unsigned char)cmd[i] < ' ')
126 if (ppid2match >= 0 && ppid2match != proc->ppid)
128 if (sid2match >= 0 && sid2match != proc->sid)
131 /* NB: OPT_INVERT is always 0 or 1 */
133 || (regexec(&re_buffer, cmd, 1, re_match, 0) == 0 /* match found */
134 && (!OPT_ANCHOR || (re_match[0].rm_so == 0 && re_match[0].rm_eo == (regoff_t)strlen(cmd)))
137 matched_pid = proc->pid;
140 cmd_last = xstrdup(cmd);
143 act(proc->pid, cmd, signo);
150 act(matched_pid, cmd_last, signo);
151 if (ENABLE_FEATURE_CLEAN_UP)
154 return matched_pid == 0; /* return 1 if no processes listed/signaled */