]> git.ipfire.org Git - thirdparty/util-linux.git/blob - misc-utils/kill.c
91cc14c9abc0ba234fa2fc88f767963b938229b5
[thirdparty/util-linux.git] / misc-utils / kill.c
1 /*
2 * Copyright (c) 1988, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33 /*
34 * oct 5 1994 -- almost entirely re-written to allow for process names.
35 * modifications (c) salvatore valente <svalente@mit.edu>
36 * may be used / modified / distributed under the same terms as the original.
37 *
38 * 1999-02-22 Arkadiusz Miƛkiewicz <misiek@pld.ORG.PL>
39 * - added Native Language Support
40 *
41 * 1999-11-13 aeb Accept signal numbers 128+s.
42 *
43 * Copyright (C) 2014 Sami Kerola <kerolasa@iki.fi>
44 * Copyright (C) 2014 Karel Zak <kzak@redhat.com>
45 */
46
47 #include <ctype.h> /* for isdigit() */
48 #include <signal.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <unistd.h>
53
54 #include "c.h"
55 #include "closestream.h"
56 #include "nls.h"
57 #include "pidfd-utils.h"
58 #include "procutils.h"
59 #include "signames.h"
60 #include "strutils.h"
61 #include "ttyutils.h"
62 #include "xalloc.h"
63
64 /* partial success, otherwise we return regular EXIT_{SUCCESS,FAILURE} */
65 #define KILL_EXIT_SOMEOK 64
66
67 enum {
68 KILL_FIELD_WIDTH = 11,
69 KILL_OUTPUT_WIDTH = 72
70 };
71
72 #ifdef UL_HAVE_PIDFD
73 # include <poll.h>
74 # include "list.h"
75 struct timeouts {
76 int period;
77 int sig;
78 struct list_head follow_ups;
79 };
80 #endif
81
82 struct kill_control {
83 char *arg;
84 pid_t pid;
85 int numsig;
86 #ifdef HAVE_SIGQUEUE
87 union sigval sigdata;
88 #endif
89 #ifdef UL_HAVE_PIDFD
90 struct list_head follow_ups;
91 #endif
92 unsigned int
93 check_all:1,
94 do_kill:1,
95 do_pid:1,
96 use_sigval:1,
97 #ifdef UL_HAVE_PIDFD
98 timeout:1,
99 #endif
100 verbose:1;
101 };
102
103 static void print_signal_name(int signum)
104 {
105 const char *name = signum_to_signame(signum);
106
107 if (name) {
108 printf("%s\n", name);
109 return;
110 }
111 #ifdef SIGRTMIN
112 if (SIGRTMIN <= signum && signum <= SIGRTMAX) {
113 printf("RT%d\n", signum - SIGRTMIN);
114 return;
115 }
116 #endif
117 printf("%d\n", signum);
118 }
119
120 static void pretty_print_signal(FILE *fp, size_t term_width, size_t *lpos,
121 int signum, const char *name)
122 {
123 if (term_width < (*lpos + KILL_FIELD_WIDTH)) {
124 fputc('\n', fp);
125 *lpos = 0;
126 }
127 *lpos += KILL_FIELD_WIDTH;
128 fprintf(fp, "%2d %-8s", signum, name);
129 }
130
131 static void print_all_signals(FILE *fp, int pretty)
132 {
133 size_t n, lth, lpos = 0, width;
134 const char *signame = NULL;
135 int signum = 0;
136
137 if (!pretty) {
138 for (n = 0; get_signame_by_idx(n, &signame, NULL) == 0; n++) {
139 lth = 1 + strlen(signame);
140 if (KILL_OUTPUT_WIDTH < lpos + lth) {
141 fputc('\n', fp);
142 lpos = 0;
143 } else if (lpos)
144 fputc(' ', fp);
145 lpos += lth;
146 fputs(signame, fp);
147 }
148 #ifdef SIGRTMIN
149 fputs(" RT<N> RTMIN+<N> RTMAX-<N>", fp);
150 #endif
151 fputc('\n', fp);
152 return;
153 }
154
155 /* pretty print */
156 width = get_terminal_width(KILL_OUTPUT_WIDTH + 1) - 1;
157 for (n = 0; get_signame_by_idx(n, &signame, &signum) == 0; n++)
158 pretty_print_signal(fp, width, &lpos, signum, signame);
159 #ifdef SIGRTMIN
160 pretty_print_signal(fp, width, &lpos, SIGRTMIN, "RTMIN");
161 pretty_print_signal(fp, width, &lpos, SIGRTMAX, "RTMAX");
162 #endif
163 fputc('\n', fp);
164 }
165
166 static void err_nosig(char *name)
167 {
168 warnx(_("unknown signal %s; valid signals:"), name);
169 print_all_signals(stderr, 1);
170 exit(EXIT_FAILURE);
171 }
172
173 static int arg_to_signum(char *arg, int maskbit)
174 {
175 int numsig;
176 char *ep;
177
178 if (isdigit(*arg)) {
179 numsig = strtol(arg, &ep, 10);
180 if (NSIG <= numsig && maskbit && (numsig & 128) != 0)
181 numsig -= 128;
182 if (*ep != 0 || numsig < 0 || NSIG <= numsig)
183 return -1;
184 return numsig;
185 }
186 return signame_to_signum(arg);
187 }
188
189 static void __attribute__((__noreturn__)) usage(void)
190 {
191 FILE *out = stdout;
192 fputs(USAGE_HEADER, out);
193 fprintf(out, _(" %s [options] <pid>|<name>...\n"), program_invocation_short_name);
194
195 fputs(USAGE_SEPARATOR, out);
196 fputs(_("Forcibly terminate a process.\n"), out);
197
198 fputs(USAGE_OPTIONS, out);
199 fputs(_(" -a, --all do not restrict the name-to-pid conversion to processes\n"
200 " with the same uid as the present process\n"), out);
201 fputs(_(" -s, --signal <signal> send this <signal> instead of SIGTERM\n"), out);
202 #ifdef HAVE_SIGQUEUE
203 fputs(_(" -q, --queue <value> use sigqueue(2), not kill(2), and pass <value> as data\n"), out);
204 #endif
205 #ifdef UL_HAVE_PIDFD
206 fputs(_(" --timeout <milliseconds> <follow-up signal>\n"
207 " wait up to timeout and send follow-up signal\n"), out);
208 #endif
209 fputs(_(" -p, --pid print pids without signaling them\n"), out);
210 fputs(_(" -l, --list[=<signal>] list signal names, or convert a signal number to a name\n"), out);
211 fputs(_(" -L, --table list signal names and numbers\n"), out);
212 fputs(_(" --verbose print pids that will be signaled\n"), out);
213
214 fputs(USAGE_SEPARATOR, out);
215 printf(USAGE_HELP_OPTIONS(24));
216 printf(USAGE_MAN_TAIL("kill(1)"));
217
218 exit(EXIT_SUCCESS);
219 }
220
221 static void __attribute__((__noreturn__)) print_kill_version(void)
222 {
223 static const char *features[] = {
224 #ifdef HAVE_SIGQUEUE
225 "sigqueue",
226 #endif
227 #ifdef UL_HAVE_PIDFD
228 "pidfd",
229 #endif
230 };
231
232 printf(_("%s from %s"), program_invocation_short_name, PACKAGE_STRING);
233
234 if (ARRAY_SIZE(features)) {
235 size_t i;
236 fputs(_(" (with: "), stdout);
237 for (i = 0; i < ARRAY_SIZE(features); i++) {
238 fputs(features[i], stdout);
239 if (i + 1 < ARRAY_SIZE(features))
240 fputs(", ", stdout);
241 }
242 fputs(")\n", stdout);
243 }
244 exit(EXIT_SUCCESS);
245 }
246
247 static char **parse_arguments(int argc, char **argv, struct kill_control *ctl)
248 {
249 char *arg;
250
251 /* Loop through the arguments. Actually, -a is the only option
252 * can be used with other options. The 'kill' is basically a
253 * one-option-at-most program. */
254 for (argc--, argv++; 0 < argc; argc--, argv++) {
255 arg = *argv;
256 if (*arg != '-')
257 break;
258 if (!strcmp(arg, "--")) {
259 argc--, argv++;
260 break;
261 }
262 if (!strcmp(arg, "-v") || !strcmp(arg, "-V") ||
263 !strcmp(arg, "--version"))
264 print_kill_version();
265 if (!strcmp(arg, "-h") || !strcmp(arg, "--help"))
266 usage();
267 if (!strcmp(arg, "--verbose")) {
268 ctl->verbose = 1;
269 continue;
270 }
271 if (!strcmp(arg, "-a") || !strcmp(arg, "--all")) {
272 ctl->check_all = 1;
273 continue;
274 }
275 if (!strcmp(arg, "-l") || !strcmp(arg, "--list")) {
276 if (argc < 2) {
277 print_all_signals(stdout, 0);
278 exit(EXIT_SUCCESS);
279 }
280 if (2 < argc)
281 errx(EXIT_FAILURE, _("too many arguments"));
282 /* argc == 2, accept "kill -l $?" */
283 arg = argv[1];
284 if ((ctl->numsig = arg_to_signum(arg, 1)) < 0)
285 errx(EXIT_FAILURE, _("unknown signal: %s"),
286 arg);
287 print_signal_name(ctl->numsig);
288 exit(EXIT_SUCCESS);
289 }
290 /* for compatibility with procps kill(1) */
291 if (!strncmp(arg, "--list=", 7) || !strncmp(arg, "-l=", 3)) {
292 char *p = strchr(arg, '=') + 1;
293 if ((ctl->numsig = arg_to_signum(p, 1)) < 0)
294 errx(EXIT_FAILURE, _("unknown signal: %s"), p);
295 print_signal_name(ctl->numsig);
296 exit(EXIT_SUCCESS);
297 }
298 if (!strcmp(arg, "-L") || !strcmp(arg, "--table")) {
299 print_all_signals(stdout, 1);
300 exit(EXIT_SUCCESS);
301 }
302 if (!strcmp(arg, "-p") || !strcmp(arg, "--pid")) {
303 ctl->do_pid = 1;
304 if (ctl->do_kill)
305 errx(EXIT_FAILURE, _("%s and %s are mutually exclusive"), "--pid", "--signal");
306 #ifdef HAVE_SIGQUEUE
307 if (ctl->use_sigval)
308 errx(EXIT_FAILURE, _("%s and %s are mutually exclusive"), "--pid", "--queue");
309 #endif
310 continue;
311 }
312 if (!strcmp(arg, "-s") || !strcmp(arg, "--signal")) {
313 if (argc < 2)
314 errx(EXIT_FAILURE, _("not enough arguments"));
315 ctl->do_kill = 1;
316 if (ctl->do_pid)
317 errx(EXIT_FAILURE, _("%s and %s are mutually exclusive"), "--pid", "--signal");
318 argc--, argv++;
319 arg = *argv;
320 if ((ctl->numsig = arg_to_signum(arg, 0)) < 0)
321 err_nosig(arg);
322 continue;
323 }
324 #ifdef HAVE_SIGQUEUE
325 if (!strcmp(arg, "-q") || !strcmp(arg, "--queue")) {
326 if (argc < 2)
327 errx(EXIT_FAILURE, _("option '%s' requires an argument"), arg);
328 if (ctl->do_pid)
329 errx(EXIT_FAILURE, _("%s and %s are mutually exclusive"), "--pid", "--queue");
330 argc--, argv++;
331 arg = *argv;
332 ctl->sigdata.sival_int = strtos32_or_err(arg, _("argument error"));
333 ctl->use_sigval = 1;
334 continue;
335 }
336 #endif
337 #ifdef UL_HAVE_PIDFD
338 if (!strcmp(arg, "--timeout")) {
339 struct timeouts *next;
340
341 ctl->timeout = 1;
342 if (argc < 2)
343 errx(EXIT_FAILURE, _("option '%s' requires an argument"), arg);
344 argc--, argv++;
345 arg = *argv;
346 next = xcalloc(1, sizeof(*next));
347 next->period = strtos32_or_err(arg, _("argument error"));
348 INIT_LIST_HEAD(&next->follow_ups);
349 argc--, argv++;
350 arg = *argv;
351 if ((next->sig = arg_to_signum(arg, 0)) < 0)
352 err_nosig(arg);
353 list_add_tail(&next->follow_ups, &ctl->follow_ups);
354 continue;
355 }
356 #endif
357 /* 'arg' begins with a dash but is not a known option.
358 * So it's probably something like -HUP, or -1/-n try to
359 * deal with it.
360 *
361 * -n could be either signal n or pid -n (a process group
362 * number). In case of doubt, POSIX tells us to assume a
363 * signal. But if a signal has already been parsed, then
364 * assume it is a process group, so stop parsing options. */
365 if (ctl->do_kill)
366 break;
367 arg++;
368 if ((ctl->numsig = arg_to_signum(arg, 0)) < 0)
369 errx(EXIT_FAILURE, _("invalid signal name or number: %s"), arg);
370 ctl->do_kill = 1;
371 if (ctl->do_pid)
372 errx(EXIT_FAILURE, _("%s and %s are mutually exclusive"), "--pid", "--signal");
373 continue;
374 }
375 if (!*argv)
376 errx(EXIT_FAILURE, _("not enough arguments"));
377 return argv;
378 }
379
380 #ifdef UL_HAVE_PIDFD
381 static int kill_with_timeout(const struct kill_control *ctl)
382 {
383 int pfd, n;
384 struct pollfd p = { 0 };
385 siginfo_t info = { 0 };
386 struct list_head *entry;
387
388 info.si_code = SI_QUEUE;
389 info.si_signo = ctl->numsig;
390 info.si_uid = getuid();
391 info.si_pid = getpid();
392 info.si_value.sival_int =
393 ctl->use_sigval != 0 ? ctl->use_sigval : ctl->numsig;
394
395 if ((pfd = pidfd_open(ctl->pid, 0)) < 0)
396 err(EXIT_FAILURE, _("pidfd_open() failed: %d"), ctl->pid);
397 p.fd = pfd;
398 p.events = POLLIN;
399
400 if (pidfd_send_signal(pfd, ctl->numsig, &info, 0) < 0)
401 err(EXIT_FAILURE, _("pidfd_send_signal() failed"));
402 list_for_each(entry, &ctl->follow_ups) {
403 struct timeouts *timeout;
404
405 timeout = list_entry(entry, struct timeouts, follow_ups);
406 n = poll(&p, 1, timeout->period);
407 if (n < 0)
408 err(EXIT_FAILURE, _("poll() failed"));
409 if (n == 0) {
410 info.si_signo = timeout->sig;
411 if (ctl->verbose)
412 printf(_("timeout, sending signal %d to pid %d\n"),
413 timeout->sig, ctl->pid);
414 if (pidfd_send_signal(pfd, timeout->sig, &info, 0) < 0)
415 err(EXIT_FAILURE, _("pidfd_send_signal() failed"));
416 }
417 }
418 return 0;
419 }
420 #endif
421
422 static int kill_verbose(const struct kill_control *ctl)
423 {
424 int rc = 0;
425
426 if (ctl->verbose)
427 printf(_("sending signal %d to pid %d\n"), ctl->numsig, ctl->pid);
428 if (ctl->do_pid) {
429 printf("%ld\n", (long) ctl->pid);
430 return 0;
431 }
432 #ifdef UL_HAVE_PIDFD
433 if (ctl->timeout) {
434 rc = kill_with_timeout(ctl);
435 } else
436 #endif
437 #ifdef HAVE_SIGQUEUE
438 if (ctl->use_sigval)
439 rc = sigqueue(ctl->pid, ctl->numsig, ctl->sigdata);
440 else
441 #endif
442 rc = kill(ctl->pid, ctl->numsig);
443
444 if (rc < 0)
445 warn(_("sending signal to %s failed"), ctl->arg);
446 return rc;
447 }
448
449 int main(int argc, char **argv)
450 {
451 struct kill_control ctl = { .numsig = SIGTERM };
452 int nerrs = 0, ct = 0;
453
454 setlocale(LC_ALL, "");
455 bindtextdomain(PACKAGE, LOCALEDIR);
456 textdomain(PACKAGE);
457 close_stdout_atexit();
458
459 INIT_LIST_HEAD(&ctl.follow_ups);
460 argv = parse_arguments(argc, argv, &ctl);
461
462 /* The rest of the arguments should be process ids and names. */
463 for ( ; (ctl.arg = *argv) != NULL; argv++) {
464 char *ep = NULL;
465
466 errno = 0;
467 ctl.pid = strtol(ctl.arg, &ep, 10);
468 if (errno == 0 && ep && *ep == '\0' && ctl.arg < ep) {
469 if (kill_verbose(&ctl) != 0)
470 nerrs++;
471 ct++;
472 } else {
473 struct proc_processes *ps = proc_open_processes();
474 int found = 0;
475
476 if (!ps)
477 continue;
478 if (!ctl.check_all)
479 proc_processes_filter_by_uid(ps, getuid());
480
481 proc_processes_filter_by_name(ps, ctl.arg);
482 while (proc_next_pid(ps, &ctl.pid) == 0) {
483 if (kill_verbose(&ctl) != 0)
484 nerrs++;
485 ct++;
486 found = 1;
487 }
488 proc_close_processes(ps);
489
490 if (!found) {
491 nerrs++, ct++;
492 warnx(_("cannot find process \"%s\""), ctl.arg);
493 }
494 }
495 }
496
497 while (!list_empty(&ctl.follow_ups)) {
498 struct timeouts *x = list_entry(ctl.follow_ups.next,
499 struct timeouts, follow_ups);
500 list_del(&x->follow_ups);
501 free(x);
502 }
503 if (ct && nerrs == 0)
504 return EXIT_SUCCESS; /* full success */
505 else if (ct == nerrs)
506 return EXIT_FAILURE; /* all failed */
507
508 return KILL_EXIT_SOMEOK; /* partial success */
509 }
510