~jkaivo/getprogname

ref: 655f41b76907269af71fd67a87cbe0391b90a99f getprogname/getprogname.c -rw-r--r-- 527 bytes
655f41b7 — Jakob Kaivo initial commit of code 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
#define _POSIX_C_SOURCE 2
#include <limits.h>
#include <stdio.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;
	}

	if (fscanf(pip, "%s", buf) != 1) {
		pclose(pip);
		return NULL;
	}

	pclose(pip);
	return buf;
}

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