~jkaivo/getprogname

ref: 88ab03ef5d6530ccd9ec1d245a1836360e7e78f6 getprogname/getprogname.c -rw-r--r-- 589 bytes
88ab03ef — Jakob Kaivo satisfy guarantee 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
#define _POSIX_C_SOURCE 2
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

char *get_program_name(size_t n, char buf[static n])
{
	char cmd[_POSIX_ARG_MAX];
	snprintf(cmd, sizeof(cmd), "ps -p %ld -o comm=", (long)getpid());

	FILE *pip = popen(cmd, "r");
	if (pip == NULL) {
		return NULL;
	}

	char *ret = fgets(pip, buf, n);
	if (ret) {
		char *nl = strchr(ret, '\n');
		if (nl) {
			*nl = '\0';
		}
	}

	pclose(pip);
	return ret;
}

char *getprogname(void)
{
	static char progname[_POSIX_NAME_MAX];
	return get_program_name(sizeof(progname), progname);
}