~sircmpwn/ctools

ref: bf7328dd1f69a415778e4be33c8c03a763ade1b2 ctools/src/nice.c -rw-r--r-- 833 bytes
bf7328dd — Adrian Perez de Castro Implement nice 2 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

static void
usage(void)
{
	fprintf(stderr, "usage: nice [-n increment] utility [argument...]\n");
}

int
main(int argc, char *argv[])
{
	int increment = 10;

	char opt;
	while ((opt = getopt(argc, argv, "n:")) != -1) {
		switch (opt) {
		case 'n': {
			char *endptr = NULL;
			long value = strtol(optarg, &endptr, 10);
			if (value < INT_MIN || value > INT_MAX
			    		|| *endptr != '\0') {
				fprintf(stderr,
					"nice: invalid increment value '%s'\n",
					optarg);
				return 1;
			}
			break;
		}
		default:
			  usage();
			  return 1;
		}
	}

	if (optind == argc) {
		usage();
		return 1;
	}

	if (nice(increment) == -1) {
		perror("nice");
	}

	if (execvp(argv[optind], argv + optind) == -1) {
		perror("execvp");
		return 1;
	}

	return 0;
}