*** empty log message ***
[platform/upstream/coreutils.git] / src / kill.c
1 /* kill -- send a signal to a process
2    Copyright (C) 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2, or (at your option)
7    any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software Foundation,
16    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
17
18 /* Written by Paul Eggert.  */
19
20 #include <config.h>
21 #include <stdio.h>
22 #include <getopt.h>
23 #include <sys/types.h>
24 #include <signal.h>
25
26 #if HAVE_SYS_WAIT_H
27 # include <sys/wait.h>
28 #endif
29 #ifndef WIFSIGNALED
30 # define WIFSIGNALED(s) (((s) & 0xFFFF) - 1 < (unsigned int) 0xFF)
31 #endif
32 #ifndef WTERMSIG
33 # define WTERMSIG(s) ((s) & 0x7F)
34 #endif
35
36 #include "system.h"
37 #include "error.h"
38 #include "sig2str.h"
39
40 /* The official name of this program (e.g., no `g' prefix).  */
41 #define PROGRAM_NAME "kill"
42
43 #define AUTHORS "Paul Eggert"
44 \f
45 #if ! (HAVE_DECL_STRTOIMAX || defined strtoimax)
46 intmax_t strtoimax ();
47 #endif
48
49 #if ! (HAVE_DECL_STRSIGNAL || defined strsignal)
50 # if ! (HAVE_DECL_SYS_SIGLIST || defined sys_siglist)
51 #  if HAVE_DECL__SYS_SIGLIST || defined _sys_siglist
52 #   define sys_siglist _sys_siglist
53 #  elif HAVE_DECL___SYS_SIGLIST || defined __sys_siglist
54 #   define sys_siglist __sys_siglist
55 #  endif
56 # endif
57 # if HAVE_DECL_SYS_SIGLIST || defined sys_siglist
58 #  define strsignal(signum) (0 <= (signum) && (signum) <= SIGNUM_BOUND \
59                              ? sys_siglist[signum] \
60                              : 0)
61 # endif
62 # ifndef strsignal
63 #  define strsignal(signum) 0
64 # endif
65 #endif
66 \f
67 /* The name this program was run with, for error messages.  */
68 char *program_name;
69
70 static char const short_options[] =
71   "0::1::2::3::4::5::6::7::8::9::"
72   "A::B::C::D::E::F::G::H::I::J::K::L::M::"
73   "N::O::P::Q::R::S::T::U::V::W::X::Y::Z::"
74   "ln:s:t";
75
76 static struct option const long_options[] =
77 {
78   {"list", no_argument, NULL, 'l'},
79   {"signal", required_argument, NULL, 's'},
80   {"table", no_argument, NULL, 't'},
81   {GETOPT_HELP_OPTION_DECL},
82   {GETOPT_VERSION_OPTION_DECL},
83   {NULL, 0, NULL, 0}
84 };
85
86 void
87 usage (int status)
88 {
89   if (status != EXIT_SUCCESS)
90     fprintf (stderr, _("Try `%s --help' for more information.\n"),
91              program_name);
92   else
93     {
94       printf (_("\
95 Usage: %s [-s SIGNAL | -SIGNAL] PID...\n\
96   or:  %s -l [SIGNAL]...\n\
97   or:  %s -t [SIGNAL]...\n\
98 "),
99               program_name, program_name, program_name);
100       fputs (_("\
101 Send signals to processes, or list signals.\n\
102 \n\
103 "), stdout);
104       fputs (_("\
105 Mandatory arguments to long options are mandatory for short options too.\n\
106 "), stdout);
107       fputs (_("\
108   -s, --signal=SIGNAL, -SIGNAL\n\
109                    specify the name or number of the signal to be sent\n\
110   -l, --list       list signal names, or convert signal names to/from numbers\n\
111   -t, --table      print a table of signal information\n\
112 "), stdout);
113       fputs (HELP_OPTION_DESCRIPTION, stdout);
114       fputs (VERSION_OPTION_DESCRIPTION, stdout);
115       fputs (_("\n\
116 SIGNAL may be a signal name like `HUP', or a signal number like `1',\n\
117 or an exit status of a process terminated by a signal.\n\
118 PID is an integer; if negative it identifies a process group.\n\
119 "), stdout);
120       printf (USAGE_BUILTIN_WARNING, PROGRAM_NAME);
121       printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
122     }
123   exit (status);
124 }
125 \f
126 /* Convert OPERAND to a signal number with printable representation SIGNAME.
127    Return the signal number, or -1 if unsuccessful.  */
128
129 static int
130 operand2sig (char const *operand, char *signame)
131 {
132   int signum;
133
134   if (ISDIGIT (*operand))
135     {
136       char *endp;
137       long int l = (errno = 0, strtol (operand, &endp, 10));
138       int i = l;
139       signum = (operand == endp || *endp || errno || i != l ? -1
140                 : WIFSIGNALED (i) ? WTERMSIG (i)
141                 : i);
142     }
143   else
144     {
145       /* Convert signal to upper case in the C locale, not in the
146          current locale.  Don't assume ASCII; it might be EBCDIC.  */
147       char *upcased = xstrdup (operand);
148       char *p;
149       for (p = upcased; *p; p++)
150         if (strchr ("abcdefghijklmnopqrstuvwxyz", *p))
151           *p += 'A' - 'a';
152
153       /* Look for the signal name, possibly prefixed by "SIG",
154          and possibly lowercased.  */
155       if (! (str2sig (upcased, &signum) == 0
156              || (upcased[0] == 'S' && upcased[1] == 'I' && upcased[2] == 'G'
157                  && str2sig (upcased + 3, &signum) == 0)))
158         signum = -1;
159
160       free (upcased);
161     }
162
163   if (signum < 0 || sig2str (signum, signame) != 0)
164     {
165       error (0, 0, _("%s: invalid signal"), operand);
166       return -1;
167     }
168
169   return signum;
170 }
171 \f
172 /* Print a row of `kill -t' output.  NUM_WIDTH is the maximum signal
173    number width, and SIGNUM is the signal number to print.  The
174    maximum name width is NAME_WIDTH, and SIGNAME is the name to print.  */
175
176 static void
177 print_table_row (unsigned int num_width, int signum,
178                  unsigned int name_width, char const *signame)
179 {
180   char const *description = strsignal (signum);
181   printf ("%*d %-*s %s\n", num_width, signum, name_width, signame,
182           description ? description : "?");
183 }
184
185 /* Print a list of signal names.  If TABLE, print a table.
186    Print the names specified by ARGV if nonzero; otherwise,
187    print all known names.  Return a suitable exit status.  */
188
189 static int
190 list_signals (bool table, char *const *argv)
191 {
192   int signum;
193   int status = EXIT_SUCCESS;
194   char signame[SIG2STR_MAX];
195
196   if (table)
197     {
198       unsigned int name_width = 0;
199
200       /* Compute the maximum width of a signal number.  */
201       unsigned int num_width = 1;
202       for (signum = 1; signum <= SIGNUM_BOUND / 10; signum *= 10)
203         num_width++;
204
205       /* Compute the maximum width of a signal name.  */
206       for (signum = 1; signum <= SIGNUM_BOUND; signum++)
207         if (sig2str (signum, signame) == 0)
208           {
209             size_t len = strlen (signame);
210             if (name_width < len)
211               name_width = len;
212           }
213
214       if (argv)
215         for (; *argv; argv++)
216           {
217             signum = operand2sig (*argv, signame);
218             if (signum < 0)
219               status = EXIT_FAILURE;
220             else
221               print_table_row (num_width, signum, name_width, signame);
222           }
223       else
224         for (signum = 1; signum <= SIGNUM_BOUND; signum++)
225           if (sig2str (signum, signame) == 0)
226             print_table_row (num_width, signum, name_width, signame);
227     }
228   else
229     {
230       if (argv)
231         for (; *argv; argv++)
232           {
233             signum = operand2sig (*argv, signame);
234             if (signum < 0)
235               status = EXIT_FAILURE;
236             else
237               {
238                 if (ISDIGIT (**argv))
239                   puts (signame);
240                 else
241                   printf ("%d\n", signum);
242               }
243           }
244       else
245         for (signum = 1; signum <= SIGNUM_BOUND; signum++)
246           if (sig2str (signum, signame) == 0)
247             puts (signame);
248     }
249
250   return status;
251 }
252 \f
253 /* Send signal SIGNUM to all the processes or process groups specified
254    by ARGV.  Return a suitable exit status.  */
255
256 static int
257 send_signals (int signum, char *const *argv)
258 {
259   int status = EXIT_SUCCESS;
260   char const *arg = *argv;
261
262   do
263     {
264       char *endp;
265       intmax_t n = (errno = 0, strtoimax (arg, &endp, 10));
266       pid_t pid = n;
267
268       if (errno == ERANGE || pid != n || arg == endp || *endp)
269         {
270           error (0, 0, _("%s: invalid process id"), arg);
271           status = EXIT_FAILURE;
272         }
273       else if (kill (pid, signum) != 0)
274         {
275           error (0, errno, "%s", arg);
276           status = EXIT_FAILURE;
277         }
278     }
279   while ((arg = *++argv));
280
281   return status;
282 }
283 \f
284 int
285 main (int argc, char **argv)
286 {
287   int optc;
288   bool list = false;
289   bool table = false;
290   int signum = -1;
291   char signame[SIG2STR_MAX];
292
293   initialize_main (&argc, &argv);
294   program_name = argv[0];
295   setlocale (LC_ALL, "");
296   bindtextdomain (PACKAGE, LOCALEDIR);
297   textdomain (PACKAGE);
298
299   atexit (close_stdout);
300
301   while ((optc = getopt_long (argc, argv, short_options, long_options, NULL))
302          != -1)
303     switch (optc)
304       {
305       case '0': case '1': case '2': case '3': case '4':
306       case '5': case '6': case '7': case '8': case '9':
307         if (optind != 2)
308           {
309             /* This option is actually a process-id.  */
310             optind--;
311             goto no_more_options;
312           }
313         /* Fall through.  */
314       case 'A': case 'B': case 'C': case 'D': case 'E':
315       case 'F': case 'G': case 'H': case 'I': case 'J':
316       case 'K': case 'L': case 'M': case 'N': case 'O':
317       case 'P': case 'Q': case 'R': case 'S': case 'T':
318       case 'U': case 'V': case 'W': case 'X': case 'Y':
319       case 'Z':
320         if (! optarg)
321           optarg = argv[optind - 1] + strlen (argv[optind - 1]);
322         if (optarg != argv[optind - 1] + 2)
323           {
324             error (0, 0, _("invalid option -- %c"), optc);
325             usage (EXIT_FAILURE);
326           }
327         optarg--;
328         /* Fall through.  */
329       case 'n': /* -n is not documented, but is for Bash compatibility.  */
330       case 's':
331         if (0 <= signum)
332           {
333             error (0, 0, _("%s: multiple signals specified"), optarg);
334             usage (EXIT_FAILURE);
335           }
336         signum = operand2sig (optarg, signame);
337         if (signum < 0)
338           usage (EXIT_FAILURE);
339         break;
340
341       case 't':
342         table = true;
343         /* Fall through.  */
344       case 'l':
345         if (list)
346           {
347             error (0, 0, _("multiple -l or -t options specified"));
348             usage (EXIT_FAILURE);
349           }
350         list = true;
351         break;
352
353       case_GETOPT_HELP_CHAR;
354       case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
355       default:
356         usage (EXIT_FAILURE);
357       }
358  no_more_options:;
359
360   if (signum < 0)
361     signum = SIGTERM;
362   else if (list)
363     {
364       error (0, 0, _("cannot combine signal with -l or -t"));
365       usage (EXIT_FAILURE);
366     }
367
368   if ( ! list && argc <= optind)
369     {
370       error (0, 0, _("no process ID specified"));
371       usage (EXIT_FAILURE);
372     }
373
374   return (list
375           ? list_signals (table, optind < argc ? argv + optind : NULL)
376           : send_signals (signum, argv + optind));
377 }