nice command in C

700 Views Asked by At

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;
}  
1

There are 1 best solutions below

0
On

You can use the exec() family of functions to replace your current process image with a new process image.

#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv)
{
    if (argc < 2) {
      /* check argc/argv to contain enough arguments */
      return EXIT_FAILURE;
    }

    /* change priority here */

    return execvp(argv[1], argv + 1);
    /* argv[0] contains the name of your current program */
    /* argv[1] contains the first command line argument */
    /* argv + 1 points to all arguments except the name of the current executable */
}

execvp will look up programs in PATH. If you require users of your program to provide the full path to the binary, use execv. In other words ./yourprogram ls will only work with execvp, not with execv. 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.