I wrote a program that realizes the equivalent of the nice
command in linux.
How can I modify the program to report the failure to stderr, take over and execute a simple command?
#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;
}
You can use the
exec()
family of functions to replace your current process image with a new process image.execvp
will look up programs in PATH. If you require users of your program to provide the full path to the binary, useexecv
. In other words./yourprogram ls
will only work withexecvp
, not withexecv
.execvp
requires you to call./yourprogram /bin/ls
.Since GNU coreutils' nice binary is open source and freely available, you can also take a look at its source code: https://github.com/coreutils/coreutils/blob/master/src/nice.c. It uses a similar
execvp
call.