I implemented the nice linux command. How can I improve the program? In terms of optimization, error handling, bugs and possible undefined behaviors
#include <stdio.h>
#include <sys/resource.h>
int my_nice(int incr)
{
/* adjusts the nicess value of a process by +incr.
Returns -1 on failure.
Returns new priority on success.
*/
int prio = getpriority(PRIO_PROCESS, 0);
if (setpriority(PRIO_PROCESS, 0, prio + incr) == -1)
return -1;
prio = getpriority(PRIO_PROCESS, 0);
return prio;
}
int main(void)
{
int prio = getpriority(PRIO_PROCESS, 0);
printf("Current priority = %d\n", prio);
printf("\nAdding +5 to the priority\n");
my_nice(5);
prio = getpriority(PRIO_PROCESS, 0);
printf("Current priority = %d\n", prio);
printf("\nAdding -7 to the priority\n");
my_nice(-7);
prio = getpriority(PRIO_PROCESS, 0);
printf("Current priority = %d\n", prio);
return 0;
}
-
\$\begingroup\$ Ref: linux.die.net/man/1/nice \$\endgroup\$chux– chux2022年06月05日 05:32:32 +00:00Commented Jun 5, 2022 at 5:32
2 Answers 2
Error paths
When getpriority(), my_nice()
returns -1, do not go on. Code should return non-zero.
Report failure
Rather than only exit on failure, print the reason why on stderr
.
Avoid naked magic number
What is special about 5, -7, 0, etc.?
// printf("\nAdding +5 to the priority\n");
// my_nice(5);
#define PRIORITY_BUMP_UP 5
printf("\nAdding %+d to the priority\n", PRIORITY_BUMP_UP);
my_nice(PRIORITY_BUMP_UP);
Repeat getpriority()
not needed
// my_nice(5);
// prio = getpriority(PRIO_PROCESS, 0);
Simplifies to
prio = my_nice(5);
Document
Useful info like "... the nice linux command." and more deserves to be in code as a comment.
Future
Add command options: help, version, alternatives to 5, 7.
Minor: style use {}
Even for simple blocks, use {}
.
if (setpriority(PRIO_PROCESS, 0, prio + incr) == -1)
{ // add
return -1;
} // add
Minor: Sentence case
// /* adjusts the nicess value of a process by +incr.
/* Adjusts the nicess value of a process by +incr.
Review spelling: "nicess".
Nice work
Better than usual Well laid out code.
"I implemented the nice linux command"
You wrote a program that modifies its own process priority. This is not event remotely what the nice
command does.
Maybe improve it by writing something like what the nice
command does.
-
\$\begingroup\$ It pretty much is the C version of that command. C has the
fork
exec
idiom, and a command like this would be thenice
equivalent. \$\endgroup\$wizzwizz4– wizzwizz42022年06月05日 17:19:15 +00:00Commented Jun 5, 2022 at 17:19 -
\$\begingroup\$ @wizzwizz4 that’s an API call. When OP says it’s a command and presents a complete program example, it’s not hard to assume it’s meant to be nice(1) rather than nice(2). Just imagine you were handed that as an assignment. I’m not even sure what you are getting at with fork/exec, other than it’s possible to then use nice(2) on the owner or child process. \$\endgroup\$Dave Meehan– Dave Meehan2022年06月05日 17:33:25 +00:00Commented Jun 5, 2022 at 17:33