/*
 *  nice_code.c
 * to compile:  cc -O -pipe   nice_code.c  -o nice_code
 */

#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include <stdlib.h>
#include <limits.h>
#include <sys/resource.h>
#include <errno.h>

#define WAYTOBIG		(100000000)

// prototypes
void print_nice();

int main(int argc, char **argv)
{
	int new_nice, foo,  err;
	unsigned register int i;

	// seed the random generator
	srand(time(NULL) );

	if( argc > 1 )
	{
		print_nice();
		
		new_nice = (int)strtol(argv[1], (char **)NULL, 10);
		/*
		 * Now set the priority to the given command line vaule. Note
		 * that only root can lower the nice value. 
		 * 
		 * The setpriority function will return 0 on success and -1 
		 * otherwise.
		 */
		err = setpriority(PRIO_PROCESS, 0, new_nice);

		if( err != 0 )
		{
			perror("Error, setpriority failed !\n");
			exit(0);
		}

		print_nice();

		// pretty useless... 
		for( i = 0; i < WAYTOBIG; i++ )
		{
			foo = rand();
		}
	}
	return(0);
}

void print_nice()
{
	int old_nice;

	/* 
	 * Clear errno before calling getpriority because 
	 * it can return -1 (which would be a valid nice value).
	 * The only way to check if the call is successful is to check errno.
	 */
	errno = 0;

	old_nice = getpriority(PRIO_PROCESS, 0);
	// check errno
	if( errno == 0 )
	{
		printf("Currently running with nice of [ %d ]\n", old_nice);
	}
	else
	{
		perror("Error, getpriority failed !\n");
		exit(0);
	}
}


syntax highlighted by Code2HTML, v. 0.9