TODO: add an item for a chmod optimization
[platform/upstream/coreutils.git] / src / nice.c
1 /* nice -- run a program with modified niceness
2    Copyright (C) 1990-2005, 2007-2008 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 3 of the License, or
7    (at your option) 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, see <http://www.gnu.org/licenses/>.  */
16
17 /* David MacKenzie <djm@gnu.ai.mit.edu> */
18
19 #include <config.h>
20 #include <stdio.h>
21 #include <getopt.h>
22 #include <sys/types.h>
23
24 #include "system.h"
25
26 #if ! HAVE_NICE
27 /* Include this after "system.h" so we're sure to have definitions
28    (from time.h or sys/time.h) required for e.g. the ru_utime member.  */
29 # include <sys/resource.h>
30 #endif
31
32 #include "error.h"
33 #include "long-options.h"
34 #include "quote.h"
35 #include "xstrtol.h"
36
37 /* The official name of this program (e.g., no `g' prefix).  */
38 #define PROGRAM_NAME "nice"
39
40 #define AUTHORS proper_name ("David MacKenzie")
41
42 #if HAVE_NICE
43 # define GET_NICENESS() nice (0)
44 #else
45 # define GET_NICENESS() getpriority (PRIO_PROCESS, 0)
46 #endif
47
48 #ifndef NZERO
49 # define NZERO 20
50 #endif
51
52 /* This is required for Darwin Kernel Version 7.7.0.  */
53 #if NZERO == 0
54 # undef  NZERO
55 # define NZERO 20
56 #endif
57
58 static struct option const longopts[] =
59 {
60   {"adjustment", required_argument, NULL, 'n'},
61   {NULL, 0, NULL, 0}
62 };
63
64 void
65 usage (int status)
66 {
67   if (status != EXIT_SUCCESS)
68     fprintf (stderr, _("Try `%s --help' for more information.\n"),
69              program_name);
70   else
71     {
72       printf (_("Usage: %s [OPTION] [COMMAND [ARG]...]\n"), program_name);
73       printf (_("\
74 Run COMMAND with an adjusted niceness, which affects process scheduling.\n\
75 With no COMMAND, print the current niceness.  Nicenesses range from\n\
76 %d (most favorable scheduling) to %d (least favorable).\n\
77 \n\
78   -n, --adjustment=N   add integer N to the niceness (default 10)\n\
79 "),
80               - NZERO, NZERO - 1);
81       fputs (HELP_OPTION_DESCRIPTION, stdout);
82       fputs (VERSION_OPTION_DESCRIPTION, stdout);
83       printf (USAGE_BUILTIN_WARNING, PROGRAM_NAME);
84       emit_bug_reporting_address ();
85     }
86   exit (status);
87 }
88
89 int
90 main (int argc, char **argv)
91 {
92   int current_niceness;
93   int adjustment = 10;
94   char const *adjustment_given = NULL;
95   bool ok;
96   int i;
97
98   initialize_main (&argc, &argv);
99   set_program_name (argv[0]);
100   setlocale (LC_ALL, "");
101   bindtextdomain (PACKAGE, LOCALEDIR);
102   textdomain (PACKAGE);
103
104   initialize_exit_failure (EXIT_FAILURE);
105   atexit (close_stdout);
106
107   parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE_NAME, Version,
108                       usage, AUTHORS, (char const *) NULL);
109
110   for (i = 1; i < argc; /* empty */)
111     {
112       char const *s = argv[i];
113
114       if (s[0] == '-' && ISDIGIT (s[1 + (s[1] == '-' || s[1] == '+')]))
115         {
116           adjustment_given = s + 1;
117           ++i;
118         }
119       else
120         {
121           int optc;
122           int fake_argc = argc - (i - 1);
123           char **fake_argv = argv + (i - 1);
124
125           /* Ensure that any getopt diagnostics use the right name.  */
126           fake_argv[0] = argv[0];
127
128           /* Initialize getopt_long's internal state.  */
129           optind = 0;
130
131           optc = getopt_long (fake_argc, fake_argv, "+n:", longopts, NULL);
132           i += optind - 1;
133
134           if (optc == '?')
135             usage (EXIT_FAILURE);
136           else if (optc == 'n')
137             adjustment_given = optarg;
138           else /* optc == -1 */
139             break;
140         }
141     }
142
143   if (adjustment_given)
144     {
145       /* If the requested adjustment is outside the valid range,
146          silently bring it to just within range; this mimics what
147          "setpriority" and "nice" do.  */
148       enum { MIN_ADJUSTMENT = 1 - 2 * NZERO, MAX_ADJUSTMENT = 2 * NZERO - 1 };
149       long int tmp;
150       if (LONGINT_OVERFLOW < xstrtol (adjustment_given, NULL, 10, &tmp, ""))
151         error (EXIT_FAILURE, 0, _("invalid adjustment %s"),
152                quote (adjustment_given));
153       adjustment = MAX (MIN_ADJUSTMENT, MIN (tmp, MAX_ADJUSTMENT));
154     }
155
156   if (i == argc)
157     {
158       if (adjustment_given)
159         {
160           error (0, 0, _("a command must be given with an adjustment"));
161           usage (EXIT_FAILURE);
162         }
163       /* No command given; print the niceness.  */
164       errno = 0;
165       current_niceness = GET_NICENESS ();
166       if (current_niceness == -1 && errno != 0)
167         error (EXIT_FAILURE, errno, _("cannot get niceness"));
168       printf ("%d\n", current_niceness);
169       exit (EXIT_SUCCESS);
170     }
171
172   errno = 0;
173 #if HAVE_NICE
174   ok = (nice (adjustment) != -1 || errno == 0);
175 #else
176   current_niceness = GET_NICENESS ();
177   if (current_niceness == -1 && errno != 0)
178     error (EXIT_FAILURE, errno, _("cannot get niceness"));
179   ok = (setpriority (PRIO_PROCESS, 0, current_niceness + adjustment) == 0);
180 #endif
181   if (!ok)
182     error (errno == EPERM ? 0 : EXIT_FAILURE, errno, _("cannot set niceness"));
183
184   execvp (argv[i], &argv[i]);
185
186   {
187     int exit_status = (errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE);
188     error (0, errno, "%s", argv[i]);
189     exit (exit_status);
190   }
191 }