summaryrefslogtreecommitdiff
path: root/src/libc/stdlib/progname.c
blob: bd90063e189bca70fc134995331226d144d35908 (plain)
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
#include <_proc.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static const char *progname;
const char *getprogname(void) {
	return progname;
}
void setprogname(const char *pg) {
	progname = pg;
	setproctitle(NULL);
}

#define DESCLEN (sizeof(_psdata_loc->desc))

void setproctitle(const char *fmt, ...) {
	char *title = NULL;

	if (fmt) {
		va_list ap;
		va_start(ap, fmt);
		int ret = vasprintf(&title, fmt, ap);
		va_end(ap);
		if (ret < 0) {
			/* strictly speaking this is unnecessary (my vasprintf already
			 * behaves like this), but I want it to be clear that if title
			 * isn't NULL, it's a valid string */
			title = NULL;
		}
	}

	if (title) {
		snprintf(_psdata_loc->desc, DESCLEN, "%s: %s", progname, title);
		free(title);
	} else {
		/* poor man's strlcpy. i do like the symmetry between the two branches
		 * though */
		snprintf(_psdata_loc->desc, DESCLEN, "%s", progname);
	}
}