hexedit: new applet
[oweals/busybox.git] / procps / kill.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini kill/killall[5] implementation for busybox
4  *
5  * Copyright (C) 1995, 1996 by Bruce Perens <bruce@pixar.com>.
6  * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
7  *
8  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
9  */
10 //config:config KILL
11 //config:       bool "kill (2.6 kb)"
12 //config:       default y
13 //config:       help
14 //config:       The command kill sends the specified signal to the specified
15 //config:       process or process group. If no signal is specified, the TERM
16 //config:       signal is sent.
17 //config:
18 //config:config KILLALL
19 //config:       bool "killall (5.6 kb)"
20 //config:       default y
21 //config:       help
22 //config:       killall sends a signal to all processes running any of the
23 //config:       specified commands. If no signal name is specified, SIGTERM is
24 //config:       sent.
25 //config:
26 //config:config KILLALL5
27 //config:       bool "killall5 (5.3 kb)"
28 //config:       default y
29 //config:       help
30 //config:       The SystemV killall command. killall5 sends a signal
31 //config:       to all processes except kernel threads and the processes
32 //config:       in its own session, so it won't kill the shell that is running
33 //config:       the script it was called from.
34
35 //applet:IF_KILL(    APPLET_NOFORK(kill,     kill, BB_DIR_BIN,      BB_SUID_DROP, kill))
36 //                   APPLET_NOFORK:name      main  location         suid_type     help
37 //applet:IF_KILLALL( APPLET_NOFORK(killall,  kill, BB_DIR_USR_BIN,  BB_SUID_DROP, killall))
38 //applet:IF_KILLALL5(APPLET_NOFORK(killall5, kill, BB_DIR_USR_SBIN, BB_SUID_DROP, killall5))
39
40 //kbuild:lib-$(CONFIG_KILL) += kill.o
41 //kbuild:lib-$(CONFIG_KILLALL) += kill.o
42 //kbuild:lib-$(CONFIG_KILLALL5) += kill.o
43
44 //usage:#define kill_trivial_usage
45 //usage:       "[-l] [-SIG] PID..."
46 //usage:#define kill_full_usage "\n\n"
47 //usage:       "Send a signal (default: TERM) to given PIDs\n"
48 //usage:     "\n        -l      List all signal names and numbers"
49 /* //usage:  "\n        -s SIG  Yet another way of specifying SIG" */
50 //usage:
51 //usage:#define kill_example_usage
52 //usage:       "$ ps | grep apache\n"
53 //usage:       "252 root     root     S [apache]\n"
54 //usage:       "263 www-data www-data S [apache]\n"
55 //usage:       "264 www-data www-data S [apache]\n"
56 //usage:       "265 www-data www-data S [apache]\n"
57 //usage:       "266 www-data www-data S [apache]\n"
58 //usage:       "267 www-data www-data S [apache]\n"
59 //usage:       "$ kill 252\n"
60 //usage:
61 //usage:#define killall_trivial_usage
62 //usage:       "[-l] [-q] [-SIG] PROCESS_NAME..."
63 //usage:#define killall_full_usage "\n\n"
64 //usage:       "Send a signal (default: TERM) to given processes\n"
65 //usage:     "\n        -l      List all signal names and numbers"
66 /* //usage:  "\n        -s SIG  Yet another way of specifying SIG" */
67 //usage:     "\n        -q      Don't complain if no processes were killed"
68 //usage:
69 //usage:#define killall_example_usage
70 //usage:       "$ killall apache\n"
71 //usage:
72 //usage:#define killall5_trivial_usage
73 //usage:       "[-l] [-SIG] [-o PID]..."
74 //usage:#define killall5_full_usage "\n\n"
75 //usage:       "Send a signal (default: TERM) to all processes outside current session\n"
76 //usage:     "\n        -l      List all signal names and numbers"
77 //usage:     "\n        -o PID  Don't signal this PID"
78 /* //usage:  "\n        -s SIG  Yet another way of specifying SIG" */
79
80 #include "libbb.h"
81
82 /* Note: kill_main is directly called from shell in order to implement
83  * kill built-in. Shell substitutes job ids with process groups first.
84  *
85  * This brings some complications:
86  *
87  * + we can't use xfunc here
88  * + we can't use applet_name
89  * + we can't use bb_show_usage
90  * (doesn't apply for killall[5], still should be careful b/c NOFORK)
91  *
92  * kill %n gets translated into kill ' -<process group>' by shell (note space!)
93  * This is needed to avoid collision with kill -9 ... syntax
94  */
95
96 //kbuild:lib-$(CONFIG_ASH_JOB_CONTROL) += kill.o
97 //kbuild:lib-$(CONFIG_HUSH_KILL) += kill.o
98
99 #define SH_KILL (ENABLE_ASH_JOB_CONTROL || ENABLE_HUSH_KILL)
100 /* If shells want to have "kill", for ifdefs it's like ENABLE_KILL=1 */
101 #if SH_KILL
102 # undef  ENABLE_KILL
103 # define ENABLE_KILL 1
104 #endif
105 #define KILL_APPLET_CNT (ENABLE_KILL + ENABLE_KILLALL + ENABLE_KILLALL5)
106
107 int kill_main(int argc UNUSED_PARAM, char **argv)
108 {
109         char *arg;
110         pid_t pid;
111         int signo = SIGTERM, errors = 0, quiet = 0;
112
113 #if KILL_APPLET_CNT == 1
114 # define is_killall  ENABLE_KILLALL
115 # define is_killall5 ENABLE_KILLALL5
116 #else
117 /* How to determine who we are? find 3rd char from the end:
118  * kill, killall, killall5
119  *  ^i       ^a        ^l  - it's unique
120  * (checking from the start is complicated by /bin/kill... case) */
121         const char char3 = argv[0][strlen(argv[0]) - 3];
122 # define is_killall  (ENABLE_KILLALL  && char3 == 'a')
123 # define is_killall5 (ENABLE_KILLALL5 && char3 == 'l')
124 #endif
125
126         /* Parse any options */
127         arg = *++argv;
128
129         if (!arg || arg[0] != '-') {
130                 goto do_it_now;
131         }
132
133         /* The -l option, which prints out signal names.
134          * Intended usage in shell:
135          * echo "Died of SIG`kill -l $?`"
136          * We try to mimic what kill from coreutils-6.8 does */
137         if (arg[1] == 'l' && arg[2] == '\0') {
138                 arg = *++argv;
139                 if (!arg) {
140                         /* Print the whole signal list */
141                         print_signames();
142                         return 0;
143                 }
144                 /* -l <sig list> */
145                 do {
146                         if (isdigit(arg[0])) {
147                                 signo = bb_strtou(arg, NULL, 10);
148                                 if (errno) {
149                                         bb_error_msg("unknown signal '%s'", arg);
150                                         return EXIT_FAILURE;
151                                 }
152                                 /* Exitcodes >= 0x80 are to be treated
153                                  * as "killed by signal (exitcode & 0x7f)" */
154                                 puts(get_signame(signo & 0x7f));
155                                 /* TODO: 'bad' signal# - coreutils says:
156                                  * kill: 127: invalid signal
157                                  * we just print "127" instead */
158                         } else {
159                                 signo = get_signum(arg);
160                                 if (signo < 0) {
161                                         bb_error_msg("unknown signal '%s'", arg);
162                                         return EXIT_FAILURE;
163                                 }
164                                 printf("%d\n", signo);
165                         }
166                         arg = *++argv;
167                 } while (arg);
168                 return EXIT_SUCCESS;
169         }
170
171         /* The -q quiet option */
172         if (is_killall && arg[1] == 'q' && arg[2] == '\0') {
173                 quiet = 1;
174                 arg = *++argv;
175                 if (!arg)
176                         bb_show_usage();
177                 if (arg[0] != '-')
178                         goto do_it_now;
179         }
180
181         arg++; /* skip '-' */
182
183         /* -o PID? (if present, it always is at the end of command line) */
184         if (is_killall5 && arg[0] == 'o')
185                 goto do_it_now;
186
187         /* "--" separates options from args. Testcase: "kill -- -123" */
188         if (!is_killall5 && arg[0] == '-' && arg[1] == '\0')
189                 goto do_it_sooner;
190
191         if (argv[1] && arg[0] == 's' && arg[1] == '\0') { /* -s SIG? */
192                 arg = *++argv;
193         } /* else it must be -SIG */
194         signo = get_signum(arg);
195         if (signo < 0) {
196                 bb_error_msg("bad signal name '%s'", arg);
197                 return EXIT_FAILURE;
198         }
199  do_it_sooner:
200         arg = *++argv;
201
202  do_it_now:
203         pid = getpid();
204
205         if (is_killall5) {
206                 pid_t sid;
207                 procps_status_t* p = NULL;
208                 /* compat: exitcode 2 is "no one was signaled" */
209                 errors = 2;
210
211                 /* Find out our session id */
212                 sid = getsid(pid);
213                 /* Stop all processes */
214                 if (signo != SIGSTOP && signo != SIGCONT)
215                         kill(-1, SIGSTOP);
216                 /* Signal all processes except those in our session */
217                 while ((p = procps_scan(p, PSSCAN_PID|PSSCAN_SID)) != NULL) {
218                         char **args;
219
220                         if (p->sid == (unsigned)sid
221                          || p->sid == 0 /* compat: kernel thread, don't signal it */
222                          || p->pid == (unsigned)pid
223                          || p->pid == 1
224                         ) {
225                                 continue;
226                         }
227
228                         /* All remaining args must be -o PID options.
229                          * Check p->pid against them. */
230                         args = argv;
231                         while (*args) {
232                                 pid_t omit;
233
234                                 arg = *args++;
235                                 if (arg[0] != '-' || arg[1] != 'o') {
236                                         bb_error_msg("bad option '%s'", arg);
237                                         errors = 1;
238                                         goto resume;
239                                 }
240                                 arg += 2;
241                                 if (!arg[0] && *args)
242                                         arg = *args++;
243                                 omit = bb_strtoi(arg, NULL, 10);
244                                 if (errno) {
245                                         bb_error_msg("invalid number '%s'", arg);
246                                         errors = 1;
247                                         goto resume;
248                                 }
249                                 if (p->pid == omit)
250                                         goto dont_kill;
251                         }
252                         kill(p->pid, signo);
253                         errors = 0;
254  dont_kill: ;
255                 }
256  resume:
257                 /* And let them continue */
258                 if (signo != SIGSTOP && signo != SIGCONT)
259                         kill(-1, SIGCONT);
260                 return errors;
261         }
262
263 #if ENABLE_KILL || ENABLE_KILLALL
264         /* Pid or name is required for kill/killall */
265         if (!arg) {
266                 bb_error_msg("you need to specify whom to kill");
267                 return EXIT_FAILURE;
268         }
269
270         if (!ENABLE_KILL || is_killall) {
271                 /* Looks like they want to do a killall.  Do that */
272                 do {
273                         pid_t* pidList;
274
275                         pidList = find_pid_by_name(arg);
276                         if (*pidList == 0) {
277                                 errors++;
278                                 if (!quiet)
279                                         bb_error_msg("%s: no process killed", arg);
280                         } else {
281                                 pid_t *pl;
282
283                                 for (pl = pidList; *pl; pl++) {
284                                         if (*pl == pid)
285                                                 continue;
286                                         if (kill(*pl, signo) == 0)
287                                                 continue;
288                                         errors++;
289                                         if (!quiet)
290                                                 bb_perror_msg("can't kill pid %d", (int)*pl);
291                                 }
292                         }
293                         free(pidList);
294                         arg = *++argv;
295                 } while (arg);
296                 return errors;
297         }
298 #endif
299
300 #if ENABLE_KILL
301         /* Looks like they want to do a kill. Do that */
302         while (arg) {
303 # if SH_KILL
304                 /*
305                  * We need to support shell's "hack formats" of
306                  * " -PRGP_ID" (yes, with a leading space)
307                  * and " PID1 PID2 PID3" (with degenerate case "")
308                  */
309                 while (*arg != '\0') {
310                         char *end;
311                         if (*arg == ' ')
312                                 arg++;
313                         pid = bb_strtoi(arg, &end, 10);
314                         if (errno && (errno != EINVAL || *end != ' ')) {
315                                 bb_error_msg("invalid number '%s'", arg);
316                                 errors++;
317                                 break;
318                         }
319                         if (kill(pid, signo) != 0) {
320                                 bb_perror_msg("can't kill pid %d", (int)pid);
321                                 errors++;
322                         }
323                         arg = end; /* can only point to ' ' or '\0' now */
324                 }
325 # else /* ENABLE_KILL but !SH_KILL */
326                 pid = bb_strtoi(arg, NULL, 10);
327                 if (errno) {
328                         bb_error_msg("invalid number '%s'", arg);
329                         errors++;
330                 } else if (kill(pid, signo) != 0) {
331                         bb_perror_msg("can't kill pid %d", (int)pid);
332                         errors++;
333                 }
334 # endif
335                 arg = *++argv;
336         }
337         return errors;
338 #endif
339 }