master xplshn/aruu / cmd / posix / getconf.c
  1/* See LICENSE file for copyright and license details. */
  2
  3
  4#include <errno.h>
  5#include <unistd.h>
  6#include <limits.h>
  7#include <stdlib.h>
  8#include <string.h>
  9
 10#include "util.h"
 11
 12struct var {
 13	const char *k;
 14	long v;
 15};
 16
 17#include "getconf.h"
 18
 19void
 20usage(void)
 21{
 22	eprintf("usage: %s [-v spec] var [path]\n", argv0);
 23}
 24
 25// ?man getconf: query configuration variables
 26// ?man arguments: var [path
 27// ?man query system configuration variables
 28int
 29main(int argc, char *argv[])
 30{
 31	size_t len;
 32	long res;
 33	size_t i;
 34	char *str;
 35
 36	ARGBEGIN {
 37	// ?man -v:str: verbose mode; show progress
 38	case 'v':
 39		/* ignore */
 40		EARGF(usage());
 41		break;
 42	default:
 43		usage();
 44		break;
 45	} ARGEND
 46
 47	if (argc == 1) {
 48		/* sysconf */
 49		for (i = 0; i < LEN(sysconf_l); i++) {
 50			if (strcmp(argv[0], sysconf_l[i].k))
 51				continue;
 52			errno = 0;
 53			if ((res = sysconf(sysconf_l[i].v)) < 0) {
 54				if (errno)
 55					eprintf("sysconf %ld:", sysconf_l[i].v);
 56				puts("undefined");
 57			} else {
 58				printf("%ld\n", res);
 59			}
 60			return fshut(stdout, "<stdout>");
 61		}
 62		/* confstr */
 63		for (i = 0; i < LEN(confstr_l); i++) {
 64			if (strcmp(argv[0], confstr_l[i].k))
 65				continue;
 66			errno = 0;
 67			if (!(len = confstr(confstr_l[i].v, NULL, 0))) {
 68				if (errno)
 69					eprintf("confstr %ld:", confstr_l[i].v);
 70				puts("undefined");
 71			} else {
 72				str = emalloc(len);
 73				errno = 0;
 74				if (!confstr(confstr_l[i].v, str, len)) {
 75					if (errno)
 76						eprintf("confstr %ld:", confstr_l[i].v);
 77					puts("undefined");
 78				} else {
 79					puts(str);
 80				}
 81				free(str);
 82			}
 83			return fshut(stdout, "<stdout>");
 84		}
 85		/* limits */
 86		for (i = 0; i < LEN(limits_l); i++) {
 87			if (strcmp(argv[0], limits_l[i].k))
 88				continue;
 89			printf("%ld\n", limits_l[i].v);
 90			return fshut(stdout, "<stdout>");
 91		}
 92	} else if (argc == 2) {
 93		/* pathconf */
 94		for (i = 0; i < LEN(pathconf_l); i++) {
 95			if (strcmp(argv[0], pathconf_l[i].k))
 96				continue;
 97			errno = 0;
 98			if ((res = pathconf(argv[1], pathconf_l[i].v)) < 0) {
 99				if (errno)
100					eprintf("pathconf %ld:", pathconf_l[i].v);
101				puts("undefined");
102			} else {
103				printf("%ld\n", res);
104			}
105			return fshut(stdout, "<stdout>");
106		}
107	} else {
108		usage();
109	}
110
111	eprintf("invalid variable: %s\n", argv[0]);
112
113	return 0;
114}